简体   繁体   English

用新数组更新React State

[英]Updating React State with new array

Trying to update my new locations state into the general one without success. 尝试将我的新位置状态更新为一般位置,但未成功。 There are 2 Components : LocationsPage and EditLocationPopup. 有2个组件: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: 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)
}

Got some trying with Object.assign but they did'nt work 尝试使用Object.assign进行操作,但没有用

You have to bind this to handleEditLocation in the LocationsPage constructor, or else this will not be what you expect when you call it from EditLocationPopup . 你必须绑定thishandleEditLocationLocationsPage构造,要不然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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM