【发布时间】:2022-01-12 16:04:58
【问题描述】:
我正在从子组件的循环 (array.map) 中调用 fetchProducts,但不想在之前已经完成时调用它。只是为了测试,我添加了“i”,我在第一次调用后更新了它,但是 this.state.i === 0 总是正确的,所以我一直在获取相同的数据。
fetchProducts = async (id) => {
if(this.state.i === 0) {
let url = "http://localhost/mysite/wp-json/mysite/product/" + id
await fetch(url)
.then(response => response.json())
.then(result => {
this.setState({
...this.state,
products: this.state.products.concat([result]),
i: 1
})
})
}
}
我在这里遗漏了什么吗?还是有更好的缓存方法?这个想法是检查 this.state.products 中的产品 ID,而不是“i”。
【问题讨论】:
标签: reactjs fetch react-state