使用新数组更新 React State
Posted
技术标签:
【中文标题】使用新数组更新 React State【英文标题】:Updating React State with new array 【发布时间】: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]) ) 注意:位置不是这里的位置,为了方便更改函数中的参数 【参考方案1】:您必须在LocationsPage
构造函数中将this
绑定到handleEditLocation
,否则当您从EditLocationPopup
调用它时,this
将不是您所期望的。
constructor(props)
super(props)
this.state =
name: '',
address: '',
longitude: '',
latitude: '',
locations: []
;
this.handleEditLocation = this.handleEditLocation.bind(this);
【讨论】:
以上是关于使用新数组更新 React State的主要内容,如果未能解决你的问题,请参考以下文章
react native 踩坑之 SectionList state更新 不执行render重新渲染页面