必须通过网络API显示项目。我成功得到了回复并显示了这些项目。但我不知道如何从列表中删除该项目。
显示每个项目的删除图标,但我无法从状态中删除该项目。我错了什么?请帮帮我。
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
posts: []
}
this.UserList = this.UserList.bind(this);
this.setStateHandler = this.setStateHandler.bind(this);
this.setDeleteHandler = this.setDeleteHandler.bind(this);
}
componentDidMount() {
this.UserList();
}
setStateHandler() {
alert(0)
var item = {
"url": "http://www.imdb.com/title/tt4937812/",
"title": "PAMMAL K SAMBANTHAM",
"imdb_id": "tt4937812",
"type": "Film",
"year": "2015"
};
var myArray = this.state.posts;
myArray.push(item)
console.log(myArray)
this.setState({posts: myArray})
};
setDeleteHandler() {
alert("idris")
};
UserList() {
alert(1)
fetch('http://www.theimdbapi.org/api/person?person_id=nm0352032').then(response => {
return response.json();
}).then(data => {
const posts = data.filmography.soundtrack;
this.setState({posts});
});
}
render() {
return (
<div>
<div>
{
this.state.posts.map((item, i) => {
return <Content item={item} key={i}/>
})
}
</div>
<button onClick = {this.setStateHandler}>SET STATE</button>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<table>
<tbody>
<tr>
<td>{this.props.item.title}</td>
<td>{this.props.item.type}</td>
<td>{this.props.item.type}</td>
<td><button onClick = {this.setDeleteHandler}>Delete</button></td>
</tr>
</tbody>
</table>
</div>
);
}
}
export default App;
有人可以帮忙吗?
谢谢。
答案 0 :(得分:1)
让你的setDeleteHandler
像这样
setDeleteHandler(index) {
return () => {
let posts = [...this.state.posts];
posts.splice(index,1);
this.setState({posts});
}
};
然后将此功能传递给您的content
组件
this.state.posts.map((item, i) => {
return <Content item={item} key={i} deleteHandler={this.setDeleteHandler(i)}/>
})
然后在你的content
组件中调用此函数
<td><button onClick = {this.props.deleteHandler}>Delete</button></td>