首页 > 解决方案 > 在状态中设置嵌套对象 - React JS

问题描述

这是我的代码:

反应 JS 代码:

class Item extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            product: [
                {
                    id: 0,
                    name: "Name",
                    price: "Quantity",

                    productIngredient: {
                        id: 0,
                        name: "Ingredient Name",
                        unit: "Unit(s)",
                        quantity: "Quantity",
                    },
                                        
                },
            ],  
        };
    }
}

export default Item;

我的问题:

在 React 中,我想设置状态,如何设置状态下的productIngredient对象?我的基本问题是如何在 React 中设置嵌套对象的状态?

标签: javascriptnode.jsreactjsreact-reduxreact-hooks

解决方案


我通常这样做:

setProductIngredient = ( productIngredient, ix ) => {
  const { product } = this.state
  product[ ix ].productIngredient = productIngredient
  this.setState( { product } )
}

如果没有索引,可以使用 find- 或 indexOf- 方法来获取正确的数组元素。


推荐阅读