简体   繁体   中英

react setState not updating the state on the UI

I have an array of items. when I type in the item number in my UI, the item will be added to the array and being displayed. I console logged and saw the item is being added into the array, but not displaying on the UI.

for example, I currently have items 1, 2, 3, 4 in array as [1, 2, 3, 4]. When I add a 5, the array will get updated as [1, 2, 3, 4, 5], but 5 is not displaying on the UI.

This is the relevant code:

export const generateItemsState = (prevState, itemErrors, testItems) => {
   const { project, items, updatedProject, validationErrors } = prevState;
   const newState = {};
   
   if (itemErrors && itemErrors.length) {
      // irelevant
   } else {
      // no item errors
      newState.updatedProject = Object.assign(updatedProject, { items: testItems });
   }
   return newState;
}

setItemsInStateAfterValidation(itemErrors, changedTestItems) {
   const newState = generateItemsState(
      this.state,
      itemErrors,
      changedTestItems
   );

   if (!itemErrors || !itemErrors.length) {
      this.setState(newState, () => {
        this.props.onUpdate(
           this.state.updatedProject
        )
      });
   } else {
      this.setState(newState);
   }
}

Please give me some guidence, thank you!

You've mutated state:

  newState.updatedPorject = Object.assign(updatedProject, { items: testItems });

First rule of react, don't mutate state. It should be:

  newState.updatedPorject = Object.assign({}, updatedProject, { items: testItems });

or equivalent:

newState.updatedPorject = { ...updatedPorject, items: testItems }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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