[英]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.