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

Tom*_*Tom 3 javascript reactjs react-router react-router-dom

我想将history道具从传递App到 Navigation 组件。当我尝试这样做时,我收到以下错误消息:

失败的道具类型:道具history在 中标记为必需Navigation,但其值为undefined

我该如何解决这个问题?

应用程序.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>
);
Run Code Online (Sandbox Code Playgroud)

主布局.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;
Run Code Online (Sandbox Code Playgroud)

Max*_*lll 5

解决方案#1:

如果您只是转换<MainLayout /><Route />渲染的a ,您将可以访问历史对象。

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

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

<App /> 无法访问历史作为道具,所以这永远不会做你想要的 <MainLayout {...props}>

解决方案#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>
);
Run Code Online (Sandbox Code Playgroud)

(history.js)

import createBrowserHistory from 'history/createBrowserHistory';

export default createBrowserHistory();
Run Code Online (Sandbox Code Playgroud)

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