[英]Updating React State with new array
尝试将我的新位置状态更新为一般位置,但未成功。 有2个组件:LocationsPage和EditLocationPopup。
位置页:
constructor(props) {
super(props)
this.state = {
name: '',
address: '',
longitude: '',
latitude: '',
locations: []
};
}
//This one does'nt work
handleEditLocation(locations) {
this.setState({ locations})
}
EditLocationPopup:
constructor(props) {
super(props);
this.state = {
name: this.props.name, //Got from other component
address: this.props.address,
longitude: this.props.longitude,
latitude: this.props.latitude
}
}
saveEditedLocation() {
const { name, address, longitude, latitude } = this.state
var id = this.props.id
var newLocation = {
id,
name,
address,
longitude,
latitude,
isToggled: false
}
var locations = this.props.locations.map(location => location.id === newLocation.id ? newLocation : location)
//locations in equal to the new locations that was updated.
//and passed to the LocationsPage
this.props.handleEditLocation(locations)
}
尝试使用Object.assign进行操作,但没有用
你必须绑定this
到handleEditLocation
在LocationsPage
构造,要不然this
不会是当你从调用它你所期望的EditLocationPopup
。
constructor(props) {
super(props)
this.state = {
name: '',
address: '',
longitude: '',
latitude: '',
locations: []
};
this.handleEditLocation = this.handleEditLocation.bind(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.