【问题标题】:routing inside code sandbox, failing due to withRouter在代码沙箱内路由,由于 withRouter 而失败
【发布时间】:2019-05-31 06:39:43
【问题描述】:

当我点击提交按钮时,我需要重定向到这个页面 pageOne,所以我用谷歌搜索并找到了一个反应路由器并使用了这一行 this.props.history.push("/anotherPage");,但它没有重定向。 它抛出一个错误不变量失败:You should not use <Route> outside a <Router> 你能告诉我如何解决它。 在下面提供我的代码 sn-p 和沙箱。

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

【问题讨论】:

标签: javascript html css reactjs redux


【解决方案1】:

您需要使用BrowserRouter 包装您的最外层组件,以便它为其子级提供所需的道具和行为。

在您的 index.js 上,将您的渲染替换为:


import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <Route exact path="/" component={Demo} />
    <Route exact path="/anotherPage" component={PageOne} />
  </BrowserRouter>, document.querySelector('#root'));

要在每个路由中渲染你的组件,请参考react router documentation

【讨论】:

  • 嘿,谢谢您的回复...我更新了代码,但仍然没有在另一个页面中显示 div。你能告诉我如何解决它吗codesandbox.io/s/material-demo-n9o7s
  • 您需要为每个要加载的路由设置一个&lt;Route /&gt;,并通过props 传递哪个组件。请参考redux.js.org/advanced/usage-with-react-router了解它,stackoverflow应该用于消除点疑惑和问题,这里不能教给你。
  • 嘿,我用 Route 更新了代码,但仍然无法正常工作...你能告诉我如何修复它吗&lt;Route exact path="/pageOne" component={PageOne} /&gt; 在此处提供我的沙箱codesandbox.io/s/material-demo-n9o7s
  • 这将允许您为不同的路由渲染不同的组件。如果最初的问题已经回答,请接受它。有关路线的更多信息,请参阅他们的文档,非常好。
猜你喜欢
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多