状态更改后,React Native ListView行不会重新呈现

时间:2015-11-12 02:36:11

标签: react-native

React Native ListView:数据源状态发生变化后,行不会重新渲染。

以下是我的代码的简化版本:

render(): {
  return <ListView
    dataSource={this.state.DS}
    renderRow={this.renderRow}/>
}

renderRow(item): {
  return <TouchableOpacity onPress={() => this.handlePress(item)}>
    {this.renderButton(item.prop1)} 
    </TouchableOpacity>
}

renderButton(prop1): {
  if (prop1 == true) {
    return <Text> Active </Text>
  } else {
    return <Text> Inactive </Text>
  }
}

handlePress(item): {
  **Change the prop1 of *item* in an array (clone of dataSource), then**
  this.setState({
    DS: this.state.DS.cloneWithRows(arrayFromAbove)
  })
}

根据Facebook的例子,ListView应该在每次更改数据源时重新呈现。是因为我只是在更改数据源中项目的属性吗?似乎renderRow函数没有重新渲染,但render()函数来自数据源的更改。

谢谢。

2 个答案:

答案 0 :(得分:7)

react足够聪明,可以检测dataSource中的更改以及是否应该重新呈现列表。如果要更新listView,请创建新对象,而不是更新现有对象的属性。 代码看起来像这样:

let newArray = this._rows.slice();
newArray[rowID] = {
  ...this._rows[rowID],
  newPropState: true,
};
this._rows = newArray;

let newDataSource = this.ds.cloneWithRows(newArray);
this.setState({
  dataSource: newDataSource
});

您可以阅读有关类似issue on Github

的更多信息

答案 1 :(得分:1)

首先,您需要在($mts/@country ! tokenize(., '\s+')) => distinct-values() 功能中设置datasource。然后,通过调用getInitialState并传入新数据源来更改数据源。看起来您可能已经在上面的正确轨道上,但我已经设置了更改 ListView 数据源here的工作示例。我希望这有帮助

https://rnplay.org/apps/r3bzOQ

相关问题