简体   繁体   English

等待 state 更新 useState 钩子

[英]Wait for state update useState hook

I have an array of objects in state: const [objects, setObjects] = useState([]);我在 state 中有一个对象数组: const [objects, setObjects] = useState([]);

I have an add button that adds an object to the array, this is the body of the onclick event:我有一个添加按钮,可将 object 添加到数组中,这是 onclick 事件的主体:

setObjects([...objects, { id: 20, property1: value1 }]);

I have a remove button that removes an object from the array, this is the body of the onclick event:我有一个删除按钮,可以从数组中删除 object,这是 onclick 事件的主体:

const newObjects = objects.filter(object => { return object.id;== idToRemove; // idToRemove comes from the onclick event }); setObjects(newObjects);

Now I want to do something with the updated state if an object gets removed from the state.现在,如果从 state 中删除 object,我想对更新的 state 做一些事情。

The problem is I have to wait till the state is updated and I don't want to listen for every state change, only if something is removed.问题是我必须等到 state 更新,我不想听每一个 state 更改,只有在删除某些东西的情况下。

This is what I have so far:这是我到目前为止所拥有的:

useEffect(() => { //execute a function that uses the updated state }, [objects.length]);

But this also fires of if an object gets added to the state.但是,如果 object 被添加到 state 中,这也会触发。

In short: I want to do something when an object gets removed from the objects array and the state is finished updating简而言之:当 object 从对象数组中删除并且 state 完成更新时,我想做一些事情

I would like to do this with hooks.我想用钩子来做这个。

Thanks in advance!提前致谢!

You could write your own hook or add some other variable that will keep the array's length and which could be used to check whether element was removed or added.您可以编写自己的钩子或添加一些其他变量来保持数组的长度,并可用于检查元素是否被删除或添加。

const [len, setLen] = useState(0);

useEffect(() => {
  if (objects.length < len) {
    // Your code
  }

  setLen(objects.length);
}, [objects.length]);

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

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