简体   繁体   English

如何将 useEffect 用于没有依赖性的 useState 变量?

[英]How to use useEffect for a useState variable that has no dependency?

I'm creating a React form that has stores new product list in a local state ie我正在创建一个 React 表单,该表单在本地 state 中存储了新产品列表,即

const [listItem, setListItem] = useState([]);

I have submit handlers where I append new value like-我已经提交处理程序,其中我 append 新值喜欢 -

const handleAddProduct = (data) => {
  setListItem ([...listItem], data)
  console.log('ListItems-', listItem); // my console log doesn't update state but in react debugger tool I do see it's updated.
}

How can use a useEffect so that it always updates state?如何使用 useEffect 使其始终更新 state? PS - data is not a local state, it's confined to a certain block. PS - 数据不是本地 state,它被限制在某个块中。

State updates are asynchronous and will not reflect immediately. State 更新是异步的,不会立即反映。 Only in next cycle.只有在下一个周期。 That is why you can check in useEffect:这就是为什么您可以签入 useEffect 的原因:

useEffect(() => {
console.log(listItem);
},[listItem]);

State is updating correctly. State 正在正确更新。

Not related to the question but, if you are adding to array you might want to do this:与问题无关,但是,如果您要添加到数组中,您可能需要这样做:

const handleAddProduct = (data) => {
setListItem ([...listItem, data]);
}

Due to Reactjs's update batching , you could not see your updated state within your event handler right after you updated it由于 Reactjs 的更新批处理,您无法在更新后立即在事件处理程序中看到更新的 state

If you want to see your value change, place it before the return function of your component:如果你想看到你的价值变化,把它放在你的组件的 return function 之前:

Something like this:是这样的:

const handleAddProduct = (data) => {
    setListItem ([...listItem], data)
}

console.log('ListItems-', listItem);

return (
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM