我正在尝试从我的状态中删除一个值。
我正在使用.filter
,因为我相信这是最简单的方法。我还想实现一个 undo
函数(但这超出了这个问题的范围)。
我已将此代码放入沙箱中 https://codesandbox.io/s/yrwo2PZ2R
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: x.movies,
};
}
remove = (e) => {
e.preventDefault();
console.log('remove movie.id:', e.target.value)
const index = e.target.value
this.setState({
movies: this.state.movies.filter((_, e) => e.id !== index)
});
}
render() {
return (
<div>
{this.state.movies.map(e =>
<div key={e.id}>
<li>{e.name} {e.id}</li>
<button value={e.id} onClick={this.remove}>remove</button>
</div>,
)}
</div>
);
}
}
最佳答案
两个问题。
首先,您从事件目标值获取的索引是一个字符串,但您正在与一个数字进行比较。更改索引声明如下:
const index = Number(e.target.value);
其次,你的过滤器有点关闭。这将起作用:
this.state.movies.filter(movie => movie.id !== index)
关于javascript - 从状态中删除值(设置新状态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44563503/