在代码沙箱内部路由,由于withRouter而失败 [英] routing inside code sandbox, failing due to withRouter
问题描述
当我按下提交按钮时,我需要重定向到此页面页面,所以我用谷歌搜索并找到了一个反应路由器并使用了这行 this.props.history.push(/ anotherPage);
,但它没有重定向。
抛出错误Invariant失败:你不应该使用< Route>在<路由器>外面
你能告诉我如何解决它。
在下面提供我的代码片段和沙箱。
When I hit submit button I need to redirect to this page pageOne, so I googled and found a react router and used this line this.props.history.push("/anotherPage");
, but its not redirecting.
Its throwing an error Invariant failed: You should not use <Route> outside a <Router>
Can you tell me how to fix it.
Providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-n9o7s
<!-- language-all: lang-or-tag-here -->
anotherPage = () => {
console.log("redictToStepper --->");
this.props.history.push("/anotherPage");
};
render() {
const { classes } = this.props;
const { checkBoxvalues } = this.state;
return (
<div className={classes.root}>increase when I hit submit button</div>
);
}
export default withRouter(withStyles(styles)(RadioButtonsGroup));
推荐答案
你需要使用<包裹最外层的组件code> BrowserRouter ,因此它会为其子女提供所需的道具和行为。
You need to wrap your most-outer component using BrowserRouter
, so it will provided the needed props and behavior to its children.
在上index.js
用以下代码替换你的渲染:
On your index.js
replace your render with:
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<Route exact path="/" component={Demo} />
<Route exact path="/anotherPage" component={PageOne} />
</BrowserRouter>, document.querySelector('#root'));
要在每条路线中渲染您的组件,请参阅反应路由器文档。
To render your components inside each route, please refer to react router documentation.
这篇关于在代码沙箱内部路由,由于withRouter而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!