我想从状态中删除项目。如何使用键从状态中删除项目
我有key
id(如this.props.result._id
)想要删除。
我想运行此函数作为fetch
(trash
函数)中的.then的结果。
这是如何实现的?
class Data extends React.Component {
render(){
const { hits } = this.props
this.components = []
return (
<div>
{hits.map(hit =>
<ItemResult ref={ref => this.components.push(ref)}
key={hit._id} result={hit} />)}
</div>
)
}
}
class ItemResult extends React.Component {
constructor(props) {
super(props);
this.deleteItem = this.deleteItem.bind(this);
this.state = {
item: props.result,
};
}
deleteItem = event => {
// console.log('This gives undefined', item)
this.setState({
item: []
})
}
render() {
return (
<div>
<button onClick={this.deleteItem.bind(this)}> Delete </button>
<h2> This appears {this.props.result.title}</h2>
</div>
);
}
}
谢谢,但它看起来像你刚刚粘贴我的代码。你能不能用实际的代码来说明这是如何完成的? – Ycon
我稍微补充了你的代码!当你创建实际的反应元素时,请检查一下,你正在添加一个独特的ID,一般以hitNum开头,然后连接任何id。然后可以在.then函数中稍后访问它,以实际删除要删除的特定元素。 –
请给出一个完整的例子,显示.then函数将其删除 - 谢谢 – Ycon