【发布时间】:2018-10-23 21:08:43
【问题描述】:
我正在尝试使用状态不应该被改变的规则来设置状态,但我不断收到错误。想不通。
这是我的状态:
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'
}
]
}
当组件挂载时,我会执行 fetch:
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));
});
}
这会返回错误: Uncaught (in promise) TypeError: Cannot convert undefined or null to object
以下作品
.then(json => {
this.setState({ jsonReturnedValue: json.printCategory.products }, () => console.log(this.state));
});
但是,根据我所读到的内容,工作人员会改变状态,这是一种不好的做法。任何帮助将不胜感激!
【问题讨论】:
-
因为 `jsonReturnedValue: null,` 您的代码试图
[...null]导致错误。所以要么初始化jsonReturnedValue: [],要么检查jsonReturnedValue是否还不是数组 -
就是这样!现在我唯一的事情是我有 jsonReturnedValue->array[0]->array[3] 所以它将另一个数组添加到数组中。我怎样才能让它只是推动阵列? @skyboyer
-
[...this.state.jsonReturnedValue, ...json.printCategory.products]
标签: javascript reactjs