【发布时间】:2019-03-29 10:24:24
【问题描述】:
我正在尝试在向数组添加键值时设置状态。我已经关注了几个问题,包括这个: How to add a new key value to react js state array?
我无法得到任何答案来应对我的挑战。
我的状态是这样的:
this.state = { jsonReturnedValue: [] }
当 componentDidMount() 我发出 fetch 请求并添加了新状态和 foreach 循环(根据上述问题的说明)
componentDidMount() {
let newState = [...this.state.jsonReturnedValue];
newState.forEach(function(file) {
file.selected = "false"
})
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));
})
.then(this.setState({jsonReturnedValue: newState}, () => console.log("selected added" + this.state) ));
}
我在想我会再次使用键值对 setState,所以我第三次添加了 .then 但它不起作用。
最终的控制台日志返回:selected added[object Object]
深入挖掘,我发现对象是空的。
编辑:我的目标是通过 api 调用设置状态,同时向每个数组添加“selected: false”的键值。
【问题讨论】:
-
无论如何,控制台日志看起来都是这样,因为您试图连接一个字符串和一个对象。因此,如果您将日志更改为
console.log('selected added', this.state),它仍然返回不正确吗? -
这没什么意义。您只想在 fetch 调用完成时设置状态?
-
我的目标是将 api 调用添加到状态,但还将“selected: false”的键/值添加到每个数组@Jared Smith
-
.then(this.setState您错误地使用了then,然后需要一个函数回调。例如...then(() => this.setState(.... -
您应该在问题中描述从 api 返回的数据结构类型以及更新后的状态应该是什么样的
标签: javascript reactjs