【发布时间】:2018-05-17 06:14:49
【问题描述】:
我有一些值存储在本地存储中。当我的组件挂载时,我想将这些值加载到状态中。但是,只有最后添加的属性会添加到状态中。我检查了我的 localStorage 上的值,它们都在那里。此外,当我在条件块中记录变量(desc、pic 或 foo)时,它们就在那里。
我起初认为每个后续 if 块都在重写状态,但事实并非如此,因为我正确使用了扩展运算符(我认为!),在所有预先存在的属性之后添加新属性。
我认为问题在于最后一个 if 块中的代码在第一个 if 块中设置状态之前运行。如何编写代码,以便将本地存储中的所有三个属性都放入状态?
//what I expect state to be
{
textArea: {
desc: 'some desc',
pic: 'some pic',
foo: 'some foo'
}
}
//what the state is
{
textArea: {
foo: 'some foo'
}
}
componentDidMount () {
const desc = window.localStorage.getItem('desc');
const pic = window.localStorage.getItem('pic');
const foo = window.localStorage.getItem('foo');
if (desc) {
console.log(desc) //'some desc'
this.setState({
...this.state,
textArea: {
...this.state.textArea,
desc: desc,
},
}, ()=>console.log(this.state.textArea.desc)); //undefined
}
if (pic) {
console.log(pic) //'some pic'
this.setState({
...this.state,
textArea: {
...this.state.textArea,
pic: pic,
},
}, ()=>console.log(this.state.textArea.pic)); //undefined
}
if (foo) {
console.log(foo) //'some foo'
this.setState({
...this.state,
textArea: {
...this.state.textArea,
foo: foo,
},
}, ()=>console.log(this.state.textArea.foo)); //'some foo'
}
}
【问题讨论】:
-
由于您调用了 3 次
setState()(异步函数),因此您每次都在覆盖状态。尝试在同一个调用中设置所有 3 个属性。 -
this.setState({ ...this.state })中不需要,因为setState只会覆盖您明确定义的内容,如果您在此处不提及 em,则不会删除 state props。
标签: javascript reactjs asynchronous setstate spread-syntax