簡體   English   中英

用新數組更新React State

[英]Updating React State with new array

嘗試將我的新位置狀態更新為一般位置,但未成功。 有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進行操作,但沒有用

你必須綁定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