我正在尝试根据放置请求更新数组
const [descriptors, setDescriptors] = useState([]);
const handleDescriptorUpdate = (id, descriptorData) => {
services
.putDescriptor(id, descriptorData)
.then((response) => {
const descriptorIndex = _.findIndex(descriptors, (e) => e.id === id);
if (descriptorIndex !== -1) {
const tempDescriptors = [...descriptors];
tempDescriptors[descriptorIndex] = response.data;
setDescriptors(tempDescriptors);
}
})
.catch((error) => {
console.error(error);
});
};
当我当时只执行 1 个请求时,这工作正常,但是当我单击执行更新两倍 promise 的按钮时,而不是传播数组并用新值更新旧值,它们都在传播相同的数组导致当第二个 promise 被解决时,它用从服务器返回的新值(第二个值)更新状态但是改变第一个值(被第一个 promise 改变的那个)恢复原值。
描述符最初填充了一个对象数组(来自 get 请求):
[
{
"id": 24,
"name": "Test 4.1",
"percentage": 0,
"towerId": "5cfc9200-c04a-11e9-89c0-2dd5d3707b1b"
},
{
"id": 23,
"name": "Test 3.1",
"percentage": 0,
"towerId": "5cfc9200-c04a-11e9-89c0-2dd5d3707b1b"
}
]
最佳答案
我看到你让描述符作为状态而不是引用,正如我在上面的评论中所说,useState 不会立即反射(reflect)更改,因此请在内存中保留数组的一个引用,你可以使用钩子(Hook) useRef 来完成,请参阅下一个例子:
const [descriptors, setDescriptors] = useState([]);
const descriptorsReference = useRef(null);
const handleDescriptorUpdate = (id, descriptorData) => {
services
.putDescriptor(id, descriptorData)
.then((response) => {
const descriptorIndex = _.findIndex(descriptors, (e) => e.id === id);
if (descriptorIndex !== -1) {
// Use descriptorsReference instead
const tempDescriptors = [...descriptorsReference.current];
tempDescriptors[descriptorIndex] = response.data;
// Next line is to update the descriptors into descriptors state, this phase doesn't happen immediately 'cause is asynchronous
setDescriptors(tempDescriptors);
// Next line is to update the descriptors in memory, this phase occurs immediately
descriptorsReference.current = tempDescriptors
}
})
.catch((error) => {
console.error(error);
});
};
关于javascript - 如何通过异步调用使用 useState Hook 来更改数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210844/