javascript 失败的道具类型道具被标记为必需,但其值为“未定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49802165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Failed prop type The prop is marked as required but its value is `undefined`
提问by AND4011002849
I'm using react v4, and I'm trying to list an array in the page "treinamentos", but I'm getting an error as I load the page:
我正在使用 react v4,并且试图在页面“treinamentos”中列出一个数组,但是在加载页面时出现错误:
Failed prop type: The prop
treinamentosis marked as required inTreinamentos, but its value isundefined.
失败的道具类型:道具
treinamentos在 中标记为必需Treinamentos,但其值为undefined。
What am I missing here? is it because of the version I'm using?
我在这里错过了什么?是因为我使用的版本吗?
Treinamentos:
特雷纳门托斯:
import React from 'react';
import TreinamentosList from './TreinamentosList';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
class Treinamentos extends React.Component {
render() {
return (
<div>
Treinamentos
<TreinamentosList treinamentos={this.props.treinamentos} />
</div>
);
}
}
Treinamentos.propTypes = {
treinamentos: PropTypes.array.isRequired
}
function mapStateToProps(state) {
return {
treinamentos: state.treinamentos
}
}
export default connect(mapStateToProps)(Treinamentos);
TreinamentosList:
TreinamentosList:
import React from 'react';
import PropTypes from 'prop-types';
export default function TreinamentosList({ treinamentos }) {
const emptyMessage = (
<p>Adicione um treinamento</p>
);
const treinamentosList = (
<p>treinamentos list</p>
);
return (
<div>
{treinamentos.length === 0 ? emptyMessage : treinamentosList}
</div>
);
}
TreinamentosList.propTypes = {
treinamentos: PropTypes.array.isRequired
}
AppRouter:
应用路由器:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Greetings from './components/Greetings';
import SignUp from './components/singup/SignUp';
import NoMatch from './components/NoMatch';
import Treinamentos from './components/Treinamentos';
import NavigationBar from './components/NavigationBar';
const AppRouter = () => (
<Router>
<div className="container">
<NavigationBar />
<Switch>
<Route path="/" component={Greetings} exact={true}/>
<Route path="/signup" component={SignUp}/>
<Route path="/treinamentos" component={Treinamentos}/>
<Route component={NoMatch}/>
</Switch>
</div>
</Router>
);
export default AppRouter;
回答by QuarK
You definitely are receiving a null object when you request the state from treinamentosreducer, you should check your reducer, return treinamentos as an empty array as a initial state (or whatever your business logic requires).
当您从treinamentos减速器请求状态时,您肯定会收到一个空对象,您应该检查减速器,将 treinamentos 作为初始状态作为空数组返回(或您的业务逻辑需要的任何内容)。


