Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

reactjs - ListView removing wrong row on dataSource update

I have a React Native ListView that seems to be removing the wrong row in the UI when I update the state with the new sections & rows - The row I deleted stays, but the one, or sometimes even, 2 below that gets removed until I reload the app.

What am I doing wrong?

constructor(props) {
  super(props)

  this.state = {
    dataState: DataState.STATE_NOT_LOADED,
    dataSource: new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1.identifier !== r2.identifier,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    })
  };
}

componentDidMount() {
  this.loadData();
}

loadData() {
  this.setState({
    dataState: DataState.STATE_LOADING
  });

  User.getDocs()
    .bind(this)
    .then(results => {
      var docs = _.groupBy(results, function (d) {
        return d.createdAt.format('MMMM D');
      });

      this.setState({
        dataState: DataState.STATE_LOADED,
        dataSource: this.state.dataSource.cloneWithRowsAndSections(docs)
      });
    })
    .catch(error => {
      console.log(error);

      this.setState({
        dataState: DataState.STATE_ERROR
      });
    });
}

onTrackPressed(doc) {
  User.untrackDoc(doc)
    .bind(this)
    .tap(() => {
      this.loadData();
    });
}

renderRow(result) {
  return (
    <DocRow
      style={styles.row}
      doc={result}
      tracked={true}
      onPress={() => this.onRowPressed(result)}
      onTrackPress={() => this.onTrackPressed(result)}/>
  );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure if this is the proper answer, but it's worked for me until I can find a better explanation/better answer.

I recently had this same question, as did someone else I was talking to. They fixed it by adding a key property to the ListView. Apparently, you need to add key to ListView because the table rows are super dynamic, and it seems like not having the key on each row was causing ListView to incorrectly choose what row to get deleted.

<ListView
  key={putSomethingUniqueInHere}
  dataSource={this.state.dataSource}
  renderRow={this.renderRow.bind(this)}
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...