【问题标题】:Cannot pass down history prop to Component无法将历史道具传递给组件
【发布时间】:2018-04-08 08:19:00
【问题描述】:

我想将history 属性从App 向下传递到导航组件。 当我尝试这样做时,我收到以下错误消息:

失败的道具类型:道具historyNavigation中标记为必填,但其值为undefined

我该如何解决这个问题?

App.js:

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

const App = props => (
  <Router>
      <MainLayout {...props}>
        <Switch>
          <Route exact name="index" path="/" component={Index}/>
          <Route component={NotFound}/>
        </Switch>
      </MainLayout>
  </Router>
);

MainLayout.js:

import React from "react";
import PropTypes from "prop-types";
import Navigation from "../../components/Navigation/Navigation";

const MainLayout = props => {
  const { children, authenticated, history } = props;

  return (
    <div>
      <Navigation authenticated={authenticated} history={history} />
      {children}
    </div>
  );
};

MainLayout.PropTypes = {
  children: PropTypes.node.isRequired,
  authenticated: PropTypes.bool.isRequired,
  history: PropTypes.object.isRequired,
};

export default MainLayout;

【问题讨论】:

  • historyMainLayout 中是否有值?您的错误表明在 Navigation 得到它时它是 undefined。似乎App 正在接收history 道具。尝试跟踪该道具并确保在传递之前对其进行定义。
  • historyMainLayout 内部的值是undefined ,但在App 内部分配了一个值

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

解决方案 #1:

如果您只是将&lt;MainLayout /&gt; 转换为渲染的&lt;Route /&gt;,您将可以访问历史对象。

<Route render={(props) => 
  <MainLayout {...props}>
    <Switch>
      <Route exact name="index" path="/" component={Index}/>
      <Route component={NotFound}/>
    </Switch>
  </MainLayout>
}/>

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js

&lt;App /&gt; 无法访问历史作为道具,因此这永远不会满足您的要求 &lt;MainLayout {...props}&gt;

解决方案 #2

您还可以在您的应用中将历史对象作为单个导出模块引用,并在您的应用中引用 React 路由器和任何其他组件/javascript 文件。

import { Router, Switch, Route } from 'react-router-dom';
import history from './history';

const App = props => (
  <Router history={history}>
      <MainLayout history={history} {...props}>
        <Switch>
          <Route exact name="index" path="/" component={Index}/>
          <Route component={NotFound}/>
        </Switch>
      </MainLayout>
  </Router>
);

(history.js)

import createBrowserHistory from 'history/createBrowserHistory';

export default createBrowserHistory();

https://www.npmjs.com/package/history

【讨论】:

  • 首先,谢谢:) 不幸的是,现在我遇到了这个问题,当我在一个元素上调用onClick={() =&gt; history.push("/")} 时,我得到Uncaught TypeError: history.push is not a function。知道我该如何解决吗? :)
  • 我的编辑应该解决您在此评论中提到的问题
【解决方案2】:

对于 react-router-dom v4

为了获得路由器组件的道具,我使用了withRouter,我想下面的更改应该可以工作,

export default wihtRouter(MainLayout);

这应该可以在 MainLayout 中使用 props.history

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2021-07-04
    • 2021-02-18
    • 2020-11-23
    相关资源
    最近更新 更多