失败的道具类型道具被标记为必需,但其值为“未定义”

时间:2018-04-12 16:55:54

标签: javascript reactjs react-redux

我正在使用react v4,我试图在页面中列出一个数组" treinamentos",但我在加载页面时遇到错误:

  

道具类型失败:道具treinamentos被标记为必需品   Treinamentos,但其值为undefined

我在这里缺少什么?是因为版本I使用?

enter image description here

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:

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;

1 个答案:

答案 0 :(得分:4)

当你从treinamentos reducer请求状态时,你肯定会收到一个空对象,你应该检查你的reducer,将treinamentos作为一个空数组返回初始状态(或者你的业务逻辑需要的任何东西)。