简体   繁体   中英

How to update React-Native listview?

I am having strange behavior when a row is being added to my listview. I am not sure where my logic is wrong. I have tabs using react-native-tab-view. On Tab 2 I am adding a object to "Favorites" array that has is being displayed on Tab 4. Before I add the object this is what is being displayed

之前

After I add the object and go back to Tab 4 this is what I am see

后

And Code

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

constructor(props) {
    super(props)
    this.state = {
      favoriteDB: props.favorites,
      renderPlaceholder: true,
      dataSource: ds.cloneWithRows([])
    }
  }

 componentDidMount() {
    InteractionManager.runAfterInteractions(() => {
      this.setState({
        dataSource: ds.cloneWithRows(this.state.favoriteDB),
        renderPlaceholder: false
      })
    })
  }

  componentWillReceiveProps(prevProps) {
    const {favorites} = this.props

    if (JSON.stringify(favorites) != JSON.stringify(prevProps.favorites)) {
      this._updateFavorites()
    }
  }

  _updateFavorites() {
    const {favorites} = this.props

    this.setState({
      favoriteDB: favorites,
      dataSource: ds.cloneWithRows(favorites)
    })
  }

 render() {
    const {dataSource} = this.state
    const {visibleHeight, visibleWidth} = this.props

    if (this.state.renderPlaceholder)
      return <Placeholder/>

    return (
      <Container theme={theme}>
        <View style={{ flex:1, height: visibleHeight - 100, width: visibleWidth }}>
          <Row>
            <Col>
              <List>
                <ListView
                  style={{ height: visibleHeight - 100, width: visibleWidth }}
                  enableEmptySections={TRUE}
                  automaticallyAdjustContentInsets={FALSE}
                  initialListSize={100}
                  pageSize={100}
                  dataSource={dataSource}
                  renderRow={rowData => this._renderRow(rowData)}/>
              </List>
            </Col>
          </Row>
        </View>
      </Container>
    )
  }

I experienced this adding and removing rows to the input of cloneWithRows with ListView as well as the data array for the new SectionList .

My workaround is to add a key for ListView that changes when the dataSource changes (name and size worked).

   return (
    <SectionList
      key={"mylistview_" + this.props.maps.length}
      style=
   ...

See https://stackoverflow.com/a/31481960/7223

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