简体   繁体   English

类型错误:this.state.contracts.map 不是函数 React

[英]TypeError: this.state.contracts.map is not a function React

I have seen this before but I still am stuck.我以前见过这个,但我仍然被卡住了。 My code where I fetch the data is as follows:我获取数据的代码如下:

 async componentDidMount(){
   try {
     const res = await 
     fetch('https://templates.accordproject.org/template-library.json');
  const data = await res.json();
  this.setState({
  contracts: data,
  });
 } catch(e) {
 console.log(e);
   }
 }

I call it here:我在这里称它:

 {this.state.contracts.map(contract => <Contract key={contract.id} contract={contract} />)}

I can see that state is:我可以看到状态是:

 contracts: 

 {
"acceptance-of-delivery@0.0.3": {
    "name": "acceptance-of-delivery",
    "description": "This clause allows the receiver of goods to inspect them for a given time period after delivery.",
    "version": "0.0.3",
    "ciceroVersion": "^0.3.0",
    "type": 1
},   /// etcv for long string of json

I get the following error:我收到以下错误:

 TypeError: this.state.contracts.map is not a function

I am fairly certain that map expects an array but this isn't one.我相当肯定 map 需要一个数组,但这不是一个。 My question is:我的问题是:

If this is the problem how do I make this.state.contracts an Array so that map will work?如果这是问题,我该如何使 this.state.contracts 成为一个数组,以便该地图可以工作?

map() is an array method. map() 是一个数组方法。 You can use您可以使用

Object.keys(this.state.contracts).map(key=>({[key]:this.state.contracts[key]}))

This will convert the object into an array of each contract.这会将对象转换为每个合约的数组。

Or, in the above example you can try:或者,在上面的示例中,您可以尝试:

Object.keys(this.state.contracts).map(key=>(<Contract key={this.state.contracts[key].id} contract={this.state.contracts[key]} />))

MDN Object.keys - Detailed on Mozilla Dev. MDN Object.keys - Mozilla Dev 上的详细信息。

Also, Object.values() and Object.entries() may help.此外, Object.values() 和 Object.entries() 可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM