我的json
this.state = {
name: '',
subCatagory: [{ name: '', price: '', customize: [] }],
};
我的地图功能
{this.state.subCatagory.map((subCatagory, idx) => (
<div className="subCatagory" key={idx}>
<input
type="text"
placeholder={`Enter Dish #${idx + 1} name`}
value={subCatagory.name}
onChange={this.handlesubCatagoryNameChange(idx)}
/>
<input
type="number"
placeholder={`subCatagory #${idx + 1} price`}
value={subCatagory.price}
onChange={this.handlesubCatagoryPriceChange(idx)}
/>
<button
type="button"
onClick={this.handleRemovesubCatagory(idx)}
className="small"
>
Delete
</button>
<button type="button" onClick={this.addNewCust(idx)} className="small">
is cust availble?
</button>
{subCatagory.customize.map((gj, f) => (
<div key={f}>
<input
type="text"
placeholder={`subCatagory #${f + 1} price`}
value={gj.name}
key={gj.key}
onChange={this._pushvaluesto_customize(f)}
/>
</div>
))}
</div>
))}
我有两个.map函数,一个用于subCatagory,然后是另一个用于自定义。,上面的代码将执行此操作
当我点击onClick={this.handleAddsubCatagory}
时,新数组将推送到this.state为name: '',subCatagory: [{ name: '', price: '', customize: [] }],
在子分类onChange={this.handlesubCatagoryNameChange(idx)}
中的名称和价格的每次文字更改,然后onChange={this.handlesubCatagoryPriceChange(idx)}
它将更新subCatagory: [{ name: '', price: '', customize: [] }],
json。,但我不知道如何更新字段自定义的值嵌套在子元素中。
我在subCatagory中更新的代码
handlesubCatagoryNameChange = idx => evt => {
const subCatagory = this.state.subCatagory.map((subCatagory, sidx) => {
if (idx !== sidx) return subCatagory;
return { ...subCatagory, name: evt.target.value };
});
this.setState({ subCatagory: subCatagory });
};
如何使用反应形式的地图更新嵌套的json
我的要点https://gist.github.com/gjgit/78bde9415b889331c9d4bfa52e4945ad
答案 0 :(得分:2)
如果已经可以访问元素的索引,那么元素值可以直接更新,如下所示,map函数将不必要地遍历数组。
这里custIdx
是自定义数组元素的索引,需要更新
handlesubCatagoryChange = (idx, property, custIdx) => evt => {
const subCatagory = this.state.subCatagory
property != 'customize'? subCategory[idx][property] = evt.target.value : subCategory[idx][property][custIdx] = evt.target.value
this.setState({ subCatagory: subCatagory });
};