javascript - 在状态中设置嵌套对象 - 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 中设置嵌套对象的状态?
解决方案
我通常这样做:
setProductIngredient = ( productIngredient, ix ) => {
const { product } = this.state
product[ ix ].productIngredient = productIngredient
this.setState( { product } )
}
如果没有索引,可以使用 find- 或 indexOf- 方法来获取正确的数组元素。
推荐阅读
- python - os.getenv() 总是返回 None
- python - 显示 -h 时的 argparse 自定义“可选参数描述”
- node.js - 如何从节点 API 访问私有 Git 存储库中的 JSON 文件
- arrays - 如何在 Angular 中使用平面数组创建树
- python - 尝试在 Heroku 上部署烧瓶应用程序,部署工作正常,直到我在我的代码中添加会话,然后它给出 500 内部错误。如何解决这个问题?
- xaml - 在 StackPanel(或任何 UIElement 而不是后面)上渲染 Win2D 阴影
- c# - 如何使视图对触摸不可见?
- c++ - Hiding C++ symbols with -fvisibility=hidden
- python - 将 Django 项目从 Windows 迁移到 Mac 迁移
- c++ - c++ 指针用作伪数组。将数字分配给没有数组的内存的多个连续位置