我试图从我的状态中删除值。从状态中删除值(设置新状态)
我使用.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>
);
}
}
这告诉我'findIndex'不是一个函数。你能在这个例子中试试吗? https://codesandbox.io/s/yrwo2PZ2R – Ycon
没有。这是删除底部项目(不是我点击的具体项目) – Ycon
不知道这是解决问题的好方法。我的意思是使用'=='而不是'==='。类型转换是更为明显的解决方案。如果你有明确的类型转换,重构错误的概率就会降低。 –