各位老哥,今天第一次自己尝试搭建使用 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": {}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.