【发布时间】:2018-04-08 08:19:00
【问题描述】:
我想将history 属性从App 向下传递到导航组件。
当我尝试这样做时,我收到以下错误消息:
失败的道具类型:道具history在Navigation中标记为必填,但其值为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;
【问题讨论】:
-
history在MainLayout中是否有值?您的错误表明在Navigation得到它时它是undefined。似乎App正在接收history道具。尝试跟踪该道具并确保在传递之前对其进行定义。 -
history在MainLayout内部的值是undefined,但在App内部分配了一个值
标签: javascript reactjs react-router react-router-dom