【问题标题】:react setState not updating the state on the UI反应 setState 不更新 UI 上的状态
【发布时间】:2021-08-24 23:44:17
【问题描述】:

我有一系列项目。当我在 UI 中输入项目编号时,该项目将被添加到数组中并被显示。我通过控制台登录并看到该项目已添加到数组中,但未显示在 UI 上。

例如,我目前在数组中的项目 1、2、3、4 为 [1、2、3、4]。当我添加 5 时,数组将更新为 [1, 2, 3, 4, 5],但 UI 上不显示 5。

这是相关代码:

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);
   }
}

请给我一些指导,谢谢!

【问题讨论】:

  • 您有 newState.updatedPorject = ...,这是一个拼写错误(pORject 与 pROject),应该是 newState.updatedProject。您是在此处发帖时才犯的错误,还是从原始代码中复制的?
  • 打错字了,抱歉

标签: javascript reactjs react-hooks setstate


【解决方案1】:

你已经改变了状态:

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

反应的第一条规则,不要改变状态。应该是:

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

或同等的:

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

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 2021-06-02
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多