[英]Copying an array from React Hook
I'm using the useState hook to populate items in an array.我正在使用 useState 钩子来填充数组中的项目。
const [meals, setMeals] = useState([]);
useEffect(async () =>{
const mealsData = await fetchMeals(localStorage.getItem('user_id'));
console.log(mealsData);// Array(3)
setMeals([...meals, mealsData]);
console.log(meals);//[]
}, []);
The array doesn't get copies in my setMeals method, what am I doing wrong here?数组在我的 setMeals 方法中没有得到副本,我在这里做错了什么?
This is because这是因为
setMeals([...meals, mealsData]);
is an asynchronous call and you are logging the meals
before being sure the state actually updated是一个异步调用,在确定状态实际更新之前,您正在记录meals
console.log(meals);
You should call and check your console.log()
function in another useEffect()
call which runs on every state change and assures that the state actually changed您应该在另一个useEffect()
调用中调用并检查您的console.log()
函数,该调用在每次状态更改时运行并确保状态实际更改
useEffect(() => {
console.log(meals);
}, [meals]);
[meals]
passed as the second argument will let this useEffect()
run every time meals
(actually) update. [meals]
作为第二个参数传递将让useEffect()
在每次meals
(实际上)更新时运行。
the update is asynchronous, the new value is not available immediately as you're expecting.更新是异步的,新值不会像您期望的那样立即可用。 You can find an in-depth explanation here: useState set method not reflecting change immediately你可以在这里找到一个深入的解释: useState set method not reflect changes directly
UseEffect cannot be async you should wrap it in an async function UseEffect 不能是异步的,你应该将它包装在一个异步函数中
function useMeals() {
const [meals, setMeals] = useState([]);
useEffect(() => {
async function setFetchedMeals() {
const mealsData = await fetchMeals(localStorage.getItem('user_id'));
setMeals([...meals, mealsData]);
}
setFetchedMeals();
}, []); // letting the dependency array empty will run the effect only once
console.log(meals)
return meals;
}
You are actually not doing anything wrong, state updates are not synchronous, so logging meals
immediately after updating it will not show the updated value您实际上没有做错任何事情,状态更新不是同步的,因此在更新后立即记录meals
不会显示更新的值
Use an effect for the meals
array to detect when it has actually changed...对meals
数组使用效果来检测它何时实际发生了变化......
useEffect(() => {
console.log(meals);
}, [meals]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.