简体   繁体   中英

Update ListView in React Native

I now there is several proposed solutions but cannot get them to work. I have problems updating the listview by making a copy of the old array correctly. My solution so far (which doesnt work :-() dont rerender the listview.

const data = [{
            id: 1,
            selected: true,
        }, {
            id: 2,
            selected: false,
        }, {
            id: 3,
            selected: false,
        }]

        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.state = {
            dataSource: ds.cloneWithRows(data),
            data: data,
        }

To update the row i use this code:

   _updateRow = (rowData, rowID) => {
    let newArray = this.state.data.slice();

    newArray.map((o, index) => {
        if (o.id = rowData.id){
            o.selected = true;
        }
        else {
            o.selected = false;
        }
    })


    this.setState({
        dataSource: this.state.dataSource.cloneWithRows(newArray),
        data: newArray
    })
}

I want to change a property (selected) from index to true and all the other objects (selected) to false. Hope someone can help. Looking for the cleanest solution.

Regards

YEAH!!! Solved it. Here are the code:

_updateRow = (rowData, rowID) => {
    let newArray = this.state.data.slice();

    newArray.map((o, index) => {
            newArray[index] = {...o, selected: true};
        else
            newArray[index] = {...o, selected: false};

    })

    this.setState({
        dataSource: this.state.dataSource.cloneWithRows(newArray),
        data: newArray
    })
}

Any one with a nicer solution?

Perhaps the code below?

 _updateRow = (rowData) => { let newArray = [].concat(this.state.data); newArray.map((o, index) => { return {...o, selected: o.id === rowData.id} }); this.setState({ dataSource: this.state.dataSource.cloneWithRows(newArray), data: newArray }) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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