在 React 的状态字典中设置字典

R O*_*OMS 9 reactjs

我有以下基于 React 的组件,它有一个字典对象 (foo),其中包含另一个字典 (bar) 的状态。

我想设置内部字典的值,但不知道该怎么做:

class App extends Component {

    state = {
        foo: {
            title: "My title",
            bar: {}
        }
    }
    componentDidMount() {
       this.state.foo.bar = { "test": "123" };
    }
}
Run Code Online (Sandbox Code Playgroud)

Dac*_*nny 13

确保通过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" };
    }
}
Run Code Online (Sandbox Code Playgroud)


har*_*isu 5

你可以这样做


componentDidMount() {
    let copyFoo = { ...this.state.foo}; //create a new copy
    copyFoo.bar = { "test": "123" } //change the value of bar
    this.setState({foo: copyFoo})//write it back to state
}
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做

componentDidMount() {
    let copyFoo = { ...this.state.foo, bar: { "test": "123" } }; //create a new copy and change the value of bar
    this.setState({foo: copyFoo})//write it back to state
}


Run Code Online (Sandbox Code Playgroud)