各位老哥,今天第一次自己尝试搭建使用 React 就碰壁了,求帮忙。 我想用 react-router-dom 和 react-router-config 搭建路由的,但是失败了。
// index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById('root')
)
// App.tsx
import React from 'react'
import {BrowserRouter as Router} from 'react-router-dom'
import {renderRoutes} from 'react-router-config'
import routes from './routes'
function App() {
return (
<Router>
{renderRoutes(routes)}
</Router>
)
}
export default App
// routes/index.ts
import Login from '../pages/Login'
import Homepage from '../pages/Homepage'
const routes = [
{
path: '/',
component: Homepage
},
{
path: '/login',
component: Login
}
]
export default routes
运行后,页面报错如下:
Error: Invariant failed: You should not use <Switch> outside a <Router>
但是我没有是使用 Switch 啊
// packages.json 如下
{
"name": "my-react-app-ts",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/react-router": "^5.1.16",
"@types/react-router-config": "^5.0.3",
"@types/react-router-dom": "^5.1.8",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router": "^5.2.0",
"react-router-config": "^5.1.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {}
}
1
XTTX 2021-08-27 11:38:23 +08:00
|
2
wiluxy 2021-08-27 12:23:33 +08:00
啊这,react-router-config 这点东西。。自己写个 renderRoutes 函数 map 一下就完事了
|
3
kenanyah 2021-08-27 13:40:30 +08:00
renderRoutes 是会创建 <Switch>的 , 所以有这个报错
你把 <Router>{renderRoutes(routes)}</Router> 外层 Router 去掉试试 |
4
17681880207 OP @kenanyah
试了一下去掉,还是报一样的错误。我看了官方的文档内,也是这么使用的 /(ㄒoㄒ)/~~ |
5
YadongZhang 2021-08-27 15:41:51 +08:00
|
6
YadongZhang 2021-08-27 15:46:46 +08:00
|
7
17681880207 OP @YadongZhang
非常感谢!后后台修改了源和尝试使用了 yarn 来进行安装,发现一切正常了。 |