我有以下基于 React 的组件,它有一个字典对象 (foo),其中包含另一个字典 (bar) 的状态。
我想设置内部字典的值,但不知道该怎么做:
class App extends Component {
state = {
foo: {
title: "My title",
bar: {}
}
}
componentDidMount() {
this.state.foo.bar = { "test": "123" };
}
}
最佳答案
确保通过 setState()
更新组件状态方法,而不是像您当前所做的那样通过直接修改。
有多种方法可以更新复杂状态结构中的嵌套数据 - 适合您的情况的简单解决方案是:
class App extends Component {
state = {
foo: {
title: "My title",
bar: {}
}
}
componentDidMount() {
// Create new "bar" object, cloning existing bar into new bar
// and updating test key with value "123"
const newBar = { ...this.state.foo.bar, test : "123" };
// Create new "foo" object, cloning existing foo into new foo
// and updating bar key with new bar object
const newFoo = { ...this.state.foo, bar : newBar };
// Calling setState() correctly updates state and triggers
// re-render. Here we replace the existing foo with the newly
// created foo object
this.setState({ foo : newFoo });
// this.state.foo.bar = { "test": "123" };
}
}
关于reactjs - 在 React 中的状态字典中设置字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58312284/