【发布时间】:2018-12-16 10:51:37
【问题描述】:
尝试将我的新位置状态更新为一般状态,但未成功。 有 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.setState({ locations: this.state.locations.concat([locationt]) }) 注意:位置不是这里的位置,为了方便更改函数中的参数
标签: javascript arrays reactjs state setstate