![](/img/trans.png)
[英]React TypeError: this.state.descriptions.map is not a function
[英]TypeError: this.state.contracts.map is not a function React
我以前见过这个,但我仍然被卡住了。 我获取数据的代码如下:
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);
}
}
我在这里称它:
{this.state.contracts.map(contract => <Contract key={contract.id} contract={contract} />)}
我可以看到状态是:
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
我收到以下错误:
TypeError: this.state.contracts.map is not a function
我相当肯定 map 需要一个数组,但这不是一个。 我的问题是:
如果这是问题,我该如何使 this.state.contracts 成为一个数组,以便该地图可以工作?
map() 是一个数组方法。 您可以使用
Object.keys(this.state.contracts).map(key=>({[key]:this.state.contracts[key]}))
这会将对象转换为每个合约的数组。
或者,在上面的示例中,您可以尝试:
Object.keys(this.state.contracts).map(key=>(<Contract key={this.state.contracts[key].id} contract={this.state.contracts[key]} />))
MDN Object.keys - Mozilla Dev 上的详细信息。
此外, Object.values() 和 Object.entries() 可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.