React-Native Updating List View DataSource

后端 未结 3 1926
借酒劲吻你
借酒劲吻你 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,
        });
    }
    
    0 讨论(0)
  • 2020-12-02 16:07

    react is smart enough to detect changes in dataSource and if the list should be re-rendered. If you want to update listView, create new objects instead of updating the properties of existing objects. The code would look something like this:

    let newArray = this._rows.slice();
    newArray[rowID] = {
      ...this._rows[rowID],
      Selection: !this._rows[rowID].Selection,
    };
    this._rows = newArray;
    
    let newDataSource = this.ds.cloneWithRows(newArray);
    this.setState({
      dataSource: newDataSource
    });
    

    You can read more about similar issue on Github

    0 讨论(0)
  • 2020-12-02 16:12

    Try this:

    pressRow(rowData){
    
        var newDs = [];
        newDs = this.state.ds.slice();
        newDs[0].Selection = newDs[0] == "AwayTeam" ? "HomeTeam" : "AwayTeam";
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(newDs)
        })
    
    }
    

    This should make a copy of the array, which can then be modified independently of the original array in this.state.ds.

    0 讨论(0)
提交回复
热议问题