无法将历史道具传递给组件

时间:2017-10-26 20:11:22

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

我想将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;

2 个答案:

答案 0 :(得分:4)

解决方案#1:

如果您只是将<MainLayout />转换为呈现的<Route />,您就可以访问历史记录对象。

<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

<App />无法访问历史作为道具,因此永远不会做您想要的事情<MainLayout {...props}>

解决方案#2

您还可以在您的应用中将历史对象引用为单个导出的模块,并在您的应用中引用React路由器和任何其他compopent / 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 createHashHistory from 'history/createBrowserHistory';

export default createHashHistory();

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

答案 1 :(得分:0)

对于react-router-dom v4

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

export default wihtRouter(MainLayout);

这应该允许在MainLayout中使用props.history