Reactjs 反应-映射处于状态的列表不会正确影响UI
我有一个处于父组件状态的列表:Reactjs 反应-映射处于状态的列表不会正确影响UI,reactjs,Reactjs,我有一个处于父组件状态的列表: this.state = { productsForm: [], } renderProducts() { const result = this.state.productsForm.map((value, index) => ( <ProductForm index={index} onChange={(name, form, strength) => {
this.state = {
productsForm: [],
}
renderProducts() {
const result = this.state.productsForm.map((value, index) => (
<ProductForm
index={index}
onChange={(name, form, strength) => {
const productsForm = this.state.productsForm;
productsForm[index] = { name, form, strength };
this.setState({ productsForm });
}}
onRemove={(id) => {
const filtered = this.state.productsForm.filter((_, i) => i !== id);
this.setState({ productsForm: filtered });
}}
/>
));
return result;
}
我在列表上执行映射并调用子组件:
this.state = {
productsForm: [],
}
renderProducts() {
const result = this.state.productsForm.map((value, index) => (
<ProductForm
index={index}
onChange={(name, form, strength) => {
const productsForm = this.state.productsForm;
productsForm[index] = { name, form, strength };
this.setState({ productsForm });
}}
onRemove={(id) => {
const filtered = this.state.productsForm.filter((_, i) => i !== id);
this.setState({ productsForm: filtered });
}}
/>
));
return result;
}
renderProducts(){
const result=this.state.productsForm.map((值,索引)=>(
{
const productsForm=this.state.productsForm;
productsForm[索引]={名称、形式、强度};
this.setState({productsForm});
}}
onRemove={(id)=>{
const filtered=this.state.productsForm.filter(((uu,i)=>i!==id);
this.setState({productsForm:filtered});
}}
/>
));
返回结果;
}
在子组件中,我有一个删除按钮,它将自身的“id”返回给父组件:
<FloatingActionButton
onClick={() => { onRemove(this.state.id); }}
>
{onRemove(this.state.id);}
>
它可以从父组件中删除子组件,但在UI中(我指的是浏览器中的html页面)存在一些问题。当我删除索引较低的子级时,尽管它将从状态中删除,但它仍保留在UI中
我认为我的代码中的“索引”或类似的东西有问题。您有什么建议我来解决这个问题吗?您忘了为每个
ProductForm
组件添加key
属性。这样,React就知道哪些组件已更改
<ProductForm key={index} ... />
如果您将
产品的id用作键而不是索引,则效果会更好 是产品表单
中的索引
键
属性吗?如果没有,则需要添加键属性。如果是,则在任何情况下使用索引
作为唯一属性都是错误的。看看这个:
数组中有三个元素
[0,1,2,3]
React通过键
道具识别它们。例如,如果从数组中删除带有1
的键,它将从数组中删除,但它将保留在UIrender
方法中。因为你的数组现在看起来像这样
[0,1,2]
带有1
的钥匙道具仍然存在。最后,这意味着您需要提供唯一的标识,例如:
key={index + somethingUnique} // worst case you can generate random numbers