简体   繁体   English

反应 setState 不更新用户界面上的 state

[英]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.我在控制台登录并看到该项目正在添加到数组中,但未显示在 UI 上。

for example, I currently have items 1, 2, 3, 4 in array as [1, 2, 3, 4].例如,我目前将数组中的项目 1、2、3、4 作为 [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.当我添加 5 时,数组将更新为 [1、2、3、4、5],但 5 未显示在 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:你改变了 state:

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

First rule of react, don't mutate state. It should be:反应的第一条规则,不要改变 state。它应该是:

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

or equivalent:或同等学历:

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

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

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