【问题标题】:react-router, The prop `history` is undefinedreact-router,道具“历史”未定义
【发布时间】:2019-02-06 03:22:07
【问题描述】:

在我的 React 应用程序中,我正在使用 react-router-dom,并且在触发功能后,我想在其中一个组件中路由到主页。 但我得到了错误

The prop `history` is marked as required in `GameElements`, but its value is `undefined`.
    in GameElements (created by Connect(GameElements))

当然还有在致电Uncaught TypeError: Cannot read property 'push' of undefined之后

这是我的 index.js

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);

从主页我到了这样的组件

<Button color="blue" as={Link} to="/GameInit">
  START GAME
</Button>

现在从GameInit我想像这样回到主页

  cancel = () => {
    const { history, cancelGame } = this.props;
    cancelGame();
    history.push("/HomePage");
  };

GameElements.propTypes = {
  cancelGame: PropTypes.func.isRequired,
  history: PropTypes.shape({
    push: PropTypes.func.isRequired
  }).isRequired,
};

取消游戏工作,它的减速器按应有的方式操纵状态

【问题讨论】:

    标签: reactjs react-router react-router-v4 browser-history react-proptypes


    【解决方案1】:

    包装你 GameElementswithRouter hoc,将它包含在你的文件中

    import { withRouter } from 'react-router'
    

    现在在底部,您导出组件的位置执行此操作。

    export default withRouter(Connect(GameElements));
    

    您可以在docs 中阅读更多信息。

    【讨论】:

    • 我的导出是通过 redux 'Connect(GameElements)' 我的问题很清楚
    • 谢谢它的工作,但我遵循这个项目风格:github.com/Remchi/bookworm-react,在这里我没有看到导出 withRouter 并且有效。例如页面/登录页面
    • 它在那里工作,因为它是路由器组件的直接后代,用于路由器组件内的嵌套组件。您需要将其包装在 withRouter 的 hoc 中
    猜你喜欢
    • 2017-08-08
    • 2017-05-22
    • 2017-08-12
    • 2018-05-14
    • 2021-08-11
    • 2019-05-09
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多