我正在尝试从我的州中删除一个值。
我正在使用.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>
);
}
}
答案 0 :(得分:2)
两个问题。
首先,您从事件目标值获取的索引是一个字符串,但您要与一个数字进行比较。更改索引声明如下:
const index = Number(e.target.value);
其次,你的过滤器有点偏。这将有效:
this.state.movies.filter(movie => movie.id !== index)
答案 1 :(得分:1)
The problem is index
has string type, but id in objects has number
type. You need type cast, for example:
const index = Number(e.target.value);
Other than that, you have some wrong _
in callback of filter
function call. You don't need it. You need:
this.state.movies.filter(e => e.id !== index)
By the way I don't recommend to name values this way. Why e
? You have array of movies. Use movie
. Why index
? You have id to remove. Then use idToRemove
name.
You also have problem with adding items.
Firstly, you can add items like this:
this.setState({
movies: [...this.state.movies, { name: item.value.name, id: item.value.id }],
})
Another point: you have to autoincrement id. You can store last value in a variable. this.idCounter
for example. And add will look like:
this.setState({
movies: [...this.state.movies, { name: item.value.name, id: this.idCounter++ }],
})
Example: https://codesandbox.io/s/2vMJQ3p5M
答案 2 :(得分:0)
您可以通过以下方式实现相同的目标
remove = (e) => {
e.preventDefault();
console.log('remove movie.id:', e.target.value)
const index = e.target.value
var movies = [...this.state.movies]
var idx = movies.findIndex((obj) => obj.id === parseInt(index))
movies.splice(idx, 1);
this.setState({
movies
});
}
在比较之前还使用parseInt将索引转换为字符串。 直接从先前的状态值设置当前状态可能会导致问题,因为setState是异步的。理想情况下,您应该使用拼接方法
创建对象的副本并删除对象<强> CODESANDBOX 强>