[英]react setState not updating the state on the UI
我有一系列项目。 当我在我的用户界面中输入项目编号时,该项目将被添加到数组中并显示出来。 我在控制台登录并看到该项目正在添加到数组中,但未显示在 UI 上。
例如,我目前将数组中的项目 1、2、3、4 作为 [1、2、3、4]。 当我添加 5 时,数组将更新为 [1、2、3、4、5],但 5 未显示在 UI 上。
这是相关代码:
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);
}
}
请大神指点一下,谢谢!
你改变了 state:
newState.updatedPorject = Object.assign(updatedProject, { items: testItems });
反应的第一条规则,不要改变 state。它应该是:
newState.updatedPorject = Object.assign({}, updatedProject, { items: testItems });
或同等学历:
newState.updatedPorject = { ...updatedPorject, items: testItems }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.