我有
const [items, setItems] = useState<any[]>(itemsB.map(() => ({ loading: true })));
和
itemsB.map(async (itemB: any, index: number) => {
searchItems(itemB).then(result => {
const newItems = [...items]; // Ref A
newItems[index] = result;
setItems(newItems);
})
})
因为内部函数是异步提取,所以项目以不可预测的顺序返回,我想在它们准备好后立即将它们添加到items
中,以实际结果更改占位符加载对象。几乎可以做到这一点,但是在Ref A处引用的items
不会更新,因此它会循环更改所有内容,最后仅显示要检索的最后一个项目。
如果我执行Promise.all().then()
,它会等到检索到所有项目以执行then
部分,因此我想知道如何在解决项目时设置它们。
答案 0 :(得分:1)
批处理对setItems的调用以优化性能。如果以前的状态依赖于当前状态,请使用setItems的重载版本,该版本将previousState作为第一个参数。
import subprocess
# Simple command
subprocess.Popen(['sort -k1 -r -n test.txt'], shell=True)
答案 1 :(得分:0)
也许这行得通:
itemsB.forEach(async (itemB: any) => {
searchItems(itemB).then(result => {
setItems(prevItems => [...prevItems, result]);
});
});
注意:这不应该在render函数中。您应该将其放在componentDidMount / Update或useEffect挂钩中。
答案 2 :(得分:0)
使用可以使用异步库来帮助您解决以下问题:
searchItems(itemB).then(result => {
setItems(items => {
const newItems = [...items]; // Ref A
newItems[index] = result;
return newItems;
});
})