【发布时间】:2017-02-08 21:32:09
【问题描述】:
我是 ReactJS 的新手,所以我尝试开发一个小应用程序来了解它是如何工作的。它是一个从 API 中获取数据(用户)并显示出来的接口。我还可以添加数据和删除用户。添加工作正常,但我在删除时遇到问题。
Json 组件(父级)
class Json extends React.Component {
constructor(props){
super(props);
this.state = {items: []}
this.updateDelete = this.updateDelete.bind(this)
this.updateAdd = this.updateAdd.bind(this)
}
componentDidMount() {
this.grabusers();
}
grabusers() {
var request = new Request('http://localhost:4000/users', {
method: 'GET',
mode: 'cors'
});
fetch(request).then(result=>result.json()).then(items=>this.setState({items: items}))
}
updateDelete(user){
var i = this.state.items.indexOf(user)
var items = this.state.items
items.splice(i,1)
this.setState({items: items})
}
updateAdd(user){
var items = this.state.items
items.push(user)
this.setState(items)
}
render(){
return (
<div>
<Form updateJson={this.updateAdd}/>
<div className="row">
{this.state.items.map(item => <Card item={item} updateJson={this.updateDelete}/>)}
</div>
</div>
)
}
}
卡片组件(子)
class Card extends React.Component {
constructor(props){
super(props)
this.state = {item: props.item}
this.delete = this.delete.bind(this)
}
delete(){
var request = new Request('http://localhost:4000/users/'+this.state.item._id, {
method: 'DELETE',
mode: 'cors'
});
fetch(request).then(() => this.props.updateJson(this.state.item))
}
render(){
return (
<div className="col-md-4">
<div className="Card row">
<div className="col-md-2"><span className="glyphicon glyphicon-user icon" aria-hidden="true"></span></div>
<div className="col-md-10"><Fullname firstname={this.state.item.firstname} lastname={this.state.item.lastname}/>
<City city={this.state.item.city}/></div>
<button type="button" className="btn btn-danger buttondelete" onClick={this.delete}>Delete</button>
</div>
</div>)
}
}
当我删除用户时,Json 的 state.items 会根据删除进行相应更新,但卡片不会相应地重新渲染。事实上,道具被传递给卡片,但它始终是从视图中删除的最后一个,而 console.log 显示一切都很好......
【问题讨论】:
-
在使用地图渲染时尝试传递密钥
-
最佳实践是将delete方法作为props从父组件传递给子组件,然后将子组件转换为纯功能组件。通过这种方式可以更轻松地管理状态。
标签: javascript api reactjs parent children