![](/img/trans.png)
[英]ES6 with React, can't setState - 'Cannot read property 'setState' of undefined'?
[英]React setState immutably in es6: cannot convert undefined or null to object
我正在嘗試使用狀態不應該突變但我不斷收到錯誤的規則來設置狀態。 無法解決這個問題。
這是我的狀態:
this.state = {
jsonReturnedValue: null,
fruit: [
{
id: 1,
title: 'Orange',
selected: false,
key: 'fruit'
},
{
id: 2,
title: 'Grape',
selected: false,
key: 'fruit'
},
{
id: 3,
title: 'Pomegranate',
selected: false,
key: 'fruit'
},
{
id: 4,
title: 'Strawberry',
selected: false,
key: 'fruit'
}
]
}
當組件掛載時,我進行提取:
componentDidMount() {
fetch('http://127.0.0.1:8000/api/printing/postcards-printing')
.then(response => response.json())
.then(json => {
this.setState({ jsonReturnedValue: [...this.state.jsonReturnedValue, json.printCategory.products] }, () => console.log(this.state));
});
}
這將返回錯誤:未捕獲(承諾)TypeError:無法將未定義或null轉換為對象
以下作品
.then(json => {
this.setState({ jsonReturnedValue: json.printCategory.products }, () => console.log(this.state));
});
然而,根據我所讀的內容,正在工作的人會改變狀態,這是一種不好的做法。 任何幫助將不勝感激!
您正在嘗試傳播一個空的原語,這是不可能的。 因此,請使用您的初始狀態執行此操作:
this.state = {
jsonReturnedValue: [],
fruit: [
{
id: 1,
title: 'Orange',
selected: false,
key: 'fruit'
},
{
id: 2,
title: 'Grape',
selected: false,
key: 'fruit'
},
{
id: 3,
title: 'Pomegranate',
selected: false,
key: 'fruit'
},
{
id: 4,
title: 'Strawberry',
selected: false,
key: 'fruit'
}
]
};
還要注意,您將要執行此操作{ jsonReturnedValue: [...this.state.jsonReturnedValue, ...json.printCategory.products] }
。 注意在數組的第二個索引中的擴展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.