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

标签 reactjs

我有以下基于 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/

相关文章:

javascript - 使用 GoLang 后端 React JS Rest API 安全性

javascript - react : passing mapped data from button onclick to display on another component

javascript - React 组件在浏览器中正确呈现,但呈现 : "Only a ReactOwner can have refs" 时 Jest 测试错误

reactjs - 在功能组件中像构造函数一样使用react

javascript - React onClick 函数在挂载时触发自身

javascript - 为所选元素分配一个类名,并在 React 中分配正确的类名

javascript - Ant Design,如何自定义Steps组件

reactjs - 我缺少什么?使用 axios 执行删除请求,使用 mongodb 作为 bakcend 通过 req.params.id 进行故障排除

javascript - 如何在 Reactjs 中将 JavaScript 与 $ inside render() 一起使用

reactjs - React 路由器不导航