我在从react.js中的对象数组中删除索引时遇到问题。
我有一个表格,显示州的数据的名称和价值。每行都有一个按钮来删除它,它的工作原理。
还有另一个按钮,用于在数组中推送HTML输入的新对象,以便用户可以添加新值。我在这里遇到的问题是删除按钮。如果我添加2或3行,则删除按钮将始终删除最后一行。
我不确定为什么删除按钮不起作用。
如果有人能提供帮助,我感激不尽。
这是代码:
class App extends Component {
constructor(props) {
super(props);
this.state = {
datas: [
{ name: 'test', value: 'test' },
{ name: 'test 1', value: 'test 1' }
]
}
}
delete = (index) => {
let datas = this.state.datas.filter((e, i) => i !== index);
this.setState({ datas : datas });
}
addnew = () => {
let datas = this.state.datas;
datas.push( {name: <input />, value: <input /> })
this.setState({ datas : datas });
}
render() {
return (
<div>
<button onClick={this.addnew}>Add</button>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.datas.map((data, index) => (
<tr key={index}>
<th>{data.name}</th>
<th>{data.value}</th>
<th><button onClick={() => this.delete(index)}>delete</button> </th>
</tr>
))}
</tbody>
</table>
</div>
);
}}
export default App;
添加行时,将初始值设置为输入元素。比删除时你正在寻找包含输入元素的对象的数组索引。函数indexOf返回第一个出现的索引。
更好的解决方案是更新删除按钮以传递元素索引删除
<th><button onClick={() => this.delete(index)}
而不仅仅是删除函数中给定索引的元素。
delete = (index) => {
let datas = this.state.datas.filter((e, i) => i !== index);
this.setState({ datas : datas });
}
但是仍然无法完全修复您的解决方案,因为您正在设置新的数组元素来保存输入元素。哪个你不应该。
我认为,问题在于使用地图索引作为关键。您可以在每个项目中拥有索引属性。
class App extends Component {
constructor(props) {
super(props);
this.state = {
datas: [
{ index:0, name: "test", value: "test" },
{ index:1, name: "test 1", value: "test 1" },
{ index:2, name: "test 2", value: "test 2" }
],
counter: 3
};
}
delete = index => {
let datas = this.state.datas.filter((e, i) => i !== index);
this.setState({ datas: datas });
};
addnew = () => {
let datas = this.state.datas;
datas.push({ index: this.state.counter, name: <input />, value: <input /> });
this.setState({ datas: datas, counter: this.state.counter + 1 });
};
render() {
return (
<div>
<button onClick={this.addnew}>Add</button>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.datas.map((data, index) => (
<tr key={data.index}>
<th>{data.name}</th>
<th>{data.value}</th>
<th>
<button onClick={() => this.delete(index)}>delete</button>{" "}
</th>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
编辑CodeSandbox:https://codesandbox.io/embed/p57now4pjx?fontsize=14