Prop在组件中标记为必需,但其值为“undefined”

时间:2017-11-08 21:44:47

标签: javascript reactjs react-router react-proptypes

single.js:

import React, { Component } from 'react';
import Details from '../components/details'
import { ProgressBar } from 'react-materialize';
import { Route, Link } from 'react-router-dom';

const Test = () => (
  <div> RENDER PAGE 1</div>
)

class SinglePage extends Component {

  constructor(props) {
    super(props);

    this.state = {
      data: null,
    }
  }

    componentDidMount() {
        fetch('http://localhost:1337/1')
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          data: json,
        });
      });
    }

  render() {

    const { data } = this.state;

    return (

      <div>

        <h2> SinglePage </h2>

        {!data ? (
          <ProgressBar />
        ) : (
          <div>
            <Details data={data} />
          </div>
        )}
      </div>
    );
  }

}

export default SinglePage;

details.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Details extends Component {

  static propTypes = {
    item: PropTypes.shape({
      date: PropTypes.string.isRequired,
    }).isRequired,
  }


    render() {
        const { item } = this.props;

        return (
            <div>
                <p> {item.date} </p>
            </div>
        )
    }
}

export default Details;

在控制台中,我收到错误:警告:道具类型失败:道具itemDetails标记为必需,但其值为undefined

从这个我虽然我的json没有被捕获,但是我有另一个组件在http://localhost:1337/上获取,获取数据并正确显示它们,然后转到http://localhost:1337/1发送一个json响应,所以我&# 39;我在这里很困惑。

其他屏幕截图:enter image description here

1 个答案:

答案 0 :(得分:2)

SinglePage传递日期道具,其名称数据与详细信息

中定义的项目相对
<Details item={date} />

还添加日期的初始值

constructor(props) {
    super(props);
    this.state = {
        date: { date: null },
    }
}