【发布时间】:2018-07-05 08:09:41
【问题描述】:
我有一个包含三个嵌套属性的状态对象,我一次只需要更新值。所以我使用 ES6 扩展语法来更新状态,但由于某种原因,每当我运行它时,它都会给我未定义的属性类型错误。
当我只有两个嵌套属性时,它工作得很好。有什么问题?
method(type, row, col) {
this.setState({
changedCells: {
...this.state.changedCells,
[type]: {
...this.state.changedCells[type],
[row]: {
...this.state.changedCells[type][row],
[col]: true
}
}
}
}
}
当 changedCells 状态最初为空时。而setState方法是这样的,用星号表示,运行良好。但是在我的第一个示例中,cellState 为空,并且 type='wood', row=0, col=0,它不起作用但在第二个示例中有效。
method(type, row, col) {
this.setState({
changedCells: {
...this.state.changedCells,
[type]: {
...this.state.changedCells[type],
[row]: {
...this.state.changedCells[row], ***CHANGED***
[col]: true
}
}
}
}
}
【问题讨论】:
-
你的状态初始值是多少?
-
this.state.changedCells[type]保证存在吗?如果不是,this.state.changedCells[type][row]总是会抛出,无论合并逻辑如何。 -
@AlexYoung 初始状态是changedCells是空的。
-
@loganfsmyth 应该保证存在。嗯,当我只做了一个关联 [index] 之前,我对代码没有任何问题,偶然有 ...this.state.changedCells[row] 而不是 ...this.state.changedCells[type][row]。所以我想这是导致问题的原因。为什么会这样?您建议如何解决?
-
为了给你一个真正的答案,我们需要一个可运行的实际功能示例。
setState等在这里无关紧要。删除它们并显示changedCells的示例以及导致错误的type和row和col示例。
标签: javascript arrays reactjs ecmascript-6 spread-syntax