用新数组更新React State

时间:2018-07-08 16:23:40

标签: javascript arrays reactjs state setstate

尝试将我的新位置状态更新为一般位置,但未成功。 有两个组件: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进行一些尝试,但是它们没有起作用

1 个答案:

答案 0 :(得分:0)

您必须在this构造函数中将handleEditLocation绑定到LocationsPage,否则从this调用EditLocationPopup时将不会像您期望的那样

constructor(props) {
    super(props)
    this.state = {
        name: '',
        address: '',
        longitude: '',
        latitude: '',
        locations: []
    };
    this.handleEditLocation = this.handleEditLocation.bind(this);
}