我是React的新手,我正在尝试使用react-router显示链接。当我在本地环境中使用代码时,它可以工作,但是当我在其他环境中(例如,在stackblitz
中使用)时,它不起作用,并且出现此错误:
您不应该在
<Link>
之外使用<Router>
您能告诉我如何修复它,以便将来自己修复吗?
这是我的Link
代码:
<Typography variant="title" id="tableTitle">
sports
<Link to={`/sports/add`}>
<IconButton variant="fab" color="secondary" aria-label="Edit" className={classes.button}>
{/* <FontAwesomeIcon style={{ margin: '10' }} size='md' icon={faPlusCircle} /> */}
</IconButton>
</Link>
</Typography>
Main.js(路由):
export default class Main extends Component {
render() {
return (
<div>
<Switch>
<Route path="/sportss/index" component={sports} />
<Route path="/sportss/add" component={sportsAdd} />
<Route path="/sportss/edit/:id" component={sportsAdd} />
<Route path="/" component={Home} />
</Switch>
</div>
)
}
}
Package.json依赖项:
"dependencies": {
"@material-ui/core": "3.3.1",
"@material-ui/icons": "^3.0.1",
"axios": "^0.18.0",
"classnames": "^2.2.6",
"gos-theme": "^2.0.0",
"lodash": "^4.17.11",
"marked": "0.3.6",
"material-ui": "0.20.2",
"prop-types": "15.5.10",
"react": "16.6.0",
"react-dom": "16.6.0",
"react-js-pagination": "^3.0.2",
"react-redux": "5.0.5",
"react-router": "3.0.5",
"react-router-dom": "^4.3.1",
"react-scripts": "^2.0.5",
"react-ultimate-pagination": "^1.2.0",
"redux": "3.7.2",
"redux-devtools-extension": "2.13.2",
"redux-form": "^7.4.2",
"redux-form-material-ui": "^4.3.4",
"redux-logger": "3.0.6",
"redux-promise": "^0.6.0",
"redux-thunk": "^2.3.0",
"styled-components": "^4.0.2",
"superagent": "3.5.2",
"superagent-promise": "1.1.0"
},
可以找到完整的应用代码here
答案 0 :(得分:0)
我对您的应用程序进行了分叉,并尝试对其进行修复。您的应用程序必须位于App.js中的BrowserRouter内,并且所使用的组件必须通过
导出withRouter
不会发生错误,但是您必须在App.js中使用Switch和Route定义了路由,以使Link指向/ sports / new。
在这里简要查看我的项目: https://github.com/dixitk13/simple-react-router/blob/master/src/App.js
您在这里编辑的项目: https://stackblitz.com/edit/react-redux-realworld-oayrtj?file=components%2FApp.js