Javascript 警告:失败的 propType:类型为 `array` 的无效 prop 预期为带有 React 的 `object`

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

Warning: Failed propType: Invalid prop of type `array` expected `object` with React

javascriptreactjs

提问by Modelesq

So this line of code is throwing something like ' Failed propType: Invalid prop of type arrayexpected object.'

所以这行代码抛出类似“失败的道具类型:array预期类型的无效道具”之类的东西object

Why is this happening?

为什么会这样?

Here is my JSON:

这是我的 JSON:

"student_records": [
      {
        "program": "PSCI-210",
        "grade": 80
      }
    ]

jsx:

jsx:

import React, { PropTypes } from 'react';


const StudentRecordPropTypes = {
  studentRecordData: PropTypes.object.isRequired,
};

function StudentRecord(props) {
    const Records = props.studentRecordData;


  return (
    <div>
        {(Records || []).map(student_records => (
              <ul>
                    <li>{student_records.program} : {student_records.grade} </li>
              </ul>
            ))}
    </div>
  );
}
StudentRecord.propTypes = StudentRecordPropTypes;

export default StudentRecord;

It displays correctly. After some googling, I realized that its looking to an array but its infact an object. My problem is that I don't know how to fix it. How can I remove this error?

它显示正确。经过一番谷歌搜索后,我意识到它在寻找一个数组,但实际上它是一个对象。我的问题是我不知道如何解决它。我怎样才能消除这个错误?

回答by QoP

Change

改变

const StudentRecordPropTypes = {
  studentRecordData: PropTypes.object.isRequired,
};

to

const StudentRecordPropTypes = {
  studentRecordData: PropTypes.array.isRequired,
};