【问题标题】:Updating React State with new array使用新数组更新 React State
【发布时间】: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


【解决方案1】:

您必须在LocationsPage 构造函数中将this 绑定到handleEditLocation,否则当您从EditLocationPopup 调用它时,this 将不是您所期望的。

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

【讨论】:

    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2021-01-17
    • 2021-09-06
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多