React-Native Updating List View DataSource

后端 未结 3 1949
借酒劲吻你
借酒劲吻你 2020-12-02 15:32

I have an iOS app I am making with react-native. The Game class contains a ListView component. I set the state in the constructor and include a dataSource. I ha

3条回答
  •  被撕碎了的回忆
    2020-12-02 16:00

    In case anyone comes across this issue like I did, here's the complete solution.

    Basically, there seems to be a bug with the ListView component and you need to rebuild each item that changes in the datasource for the ListView to redraw it.

    First, create the datasource and a copy of the array and save them to state. In my case, foods is the array.

    constructor(props){
        super(props);
        var ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        this.state = {
            dataSource: ds.cloneWithRows(foods),
            db: foods,
        };
    }
    

    When you want to change something in the datasource, make a copy of the array you saved to the state, rebuild the item with the change and then save the new array with the change back to the state (both db and datasource).

    onCollapse(rowID: number) {
        console.log("rowID", rowID);
        var newArray = this.state.db.slice();
        newArray[rowID] = {
            key: newArray[rowID].key,
            details: newArray[rowID].details,
            isCollapsed: newArray[rowID].isCollapsed == false ? true : false,
        };
        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(newArray),
            db: newArray,
        });
    }
    

提交回复
热议问题