尝试将我的新位置状态更新为一般位置,但未成功。 有两个组件:LocationsPage和EditLocationPopup。
LocationsPage:
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进行一些尝试,但是它们没有起作用
答案 0 :(得分:0)
您必须在this
构造函数中将handleEditLocation
绑定到LocationsPage
,否则从this
调用EditLocationPopup
时将不会像您期望的那样
constructor(props) {
super(props)
this.state = {
name: '',
address: '',
longitude: '',
latitude: '',
locations: []
};
this.handleEditLocation = this.handleEditLocation.bind(this);
}