问题
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