routing inside code sandbox, failing due to withRouter

荒凉一梦 提交于 2019-12-22 18:47:23

问题


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));

回答1:


You need to wrap your most-outer component using BrowserRouter, so it will provided the needed props and behavior to its children.

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.



来源:https://stackoverflow.com/questions/56383755/routing-inside-code-sandbox-failing-due-to-withrouter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!