React is sending old state to its parent

血红的双手。 提交于 2019-12-03 16:45:20

The reason parent gets the old value of selecteditems, is because setState() is an asynchronous operation. See explanation here:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

So in your code, you send a request to update state, and before the new state is processed, you call the method in the parent, to inform parent about state, which still has the old items.

Fix 1: send current state to parent.
To get the item to send the current state, you could use the callback that setState() provides. Explained also in react pages:

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered.

This ensures that the call to parent is made only after setState() is finished. Something like this:

this.setState(
  {
    title: item,
    selectedItems: selectedItems,
    open: false
  },
  this.sendStateToParent
);

Fix 2(optional but recommended): move selecteditems state to parent.
If your parent needs to know about selecteditems, I would advise not to put these in state of the list. The only thing your component does with the selecteditems is to send them to the parent, every time an item is clicked.
Instead, it is better to:

  • put selectedItems in state of the parent
  • from the parent, pass selectedItems as props to the component
  • move the handleItemClick logic to the parent
  • inside the parent, you update the list of selectedItems, and set state (of the parent)
  • triggering a re-render of the list, with the new selectedItems as props
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!