Javascript Prop 在组件中被标记为 required,但它的值为 `undefined`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47190223/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:46:25  来源:igfitidea点击:

Prop is marked as required in component, but its value is `undefined`

javascriptreactjsreact-routerreact-proptypes

提问by Charles Duporge

single.js :

单.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 :

细节.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;

In console, I am getting an error : Warning: Failed prop type: The prop itemis marked as required in Details, but its value is undefined.

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

From this I though my json was not catched but I have an other component which fetch on http://localhost:1337/, get datas and display them correctly, and going to http://localhost:1337/1send me a json response so I'm quite confused here.

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

Additional screenshot : enter image description here

附加屏幕截图: 在此处输入图片说明

采纳答案by Shawn Janas

SinglePage is passing date props with name data as oppose to item that is defined in Details

SinglePage 正在传递带有名称数据的日期道具作为与详细信息中定义的项目相反的项目

<Details item={date} />

Also adding init value for date

还为日期添加初始值

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