import { useEffect, useState } from "react";
import { v4 as uuidv4 } from 'uuid';
interface Item {
id: string,
value: number
}
function App() {
const [list, setList] = useState<Item[]>([]);
useEffect(() => {
console.log(list);
}, [list])
function createItem() {
const id = uuidv4();
setList([...list, { id: id, value: 1 }]);
return id;
}
function updateItem(index: number, value: number) {
var newArray = [...list];
newArray[index].value = value;
setList(newArray);
}
async function process() {
const id = createItem()
const index = list.findIndex(item => item.id === id);
// Error starts here because list is empty (?)
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 10000)));
updateItem(index, 2);
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 10000)));
updateItem(index, 3)
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 10000)));
updateItem(index, 4)
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 10000)));
updateItem(index, 5)
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 10000)));
}
return (
<div className="App">
<button onClick={() => {
process();
}}>Create</button>
{list.map((item) => {
return <p key={item.id}>{item.value}</p>
})}
</div>
);
}
export default App;
我试图创建一个有状态数组,但所有数组元素都应该分别更新自己的状态.
假设:
但当我使用上面的代码时,它在try 查找索引之后就出现了错误.有一段时间,它正在工作,但由于[…列表,项]的原因,项正在覆盖彼此的状态.这可能是因为以前创建的不知道新的.
我完全糊涂了.我只想有一个有状态数组,其中所有元素各自更新自己的状态.
一种解决方法是为项目创建一个新组件,并让它存储/更新自己的数据,但我需要在不创建新组件的情况下执行此操作.