我在将Firebase与React-Native集成时遇到了问题。下面的代码没有像我预期的那样生成列表视图。我的假设是messages.val()没有返回正确的格式。当我尝试控制日志"消息"变量返回如下
Object {text: "hello world", user_id: 1}
代码:
class Test extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
})
};
}
componentWillMount() {
this.dataRef = new Firebase("https://dummy.firebaseio.com/");
this.dataRef.on('child_added', function(snapshot){
var messages = snapshot.val();
this.setState({
dataSource: this.state.dataSource.cloneWithRows(messages)
});
}.bind(this));
}
renderRow(rowData, sectionID, rowID) {
console.log(this.state.dataSource);
return (
<TouchableHighlight
underlayColor='#dddddd'>
<View>
<Text>{rowData.user_id}</Text>
<Text>{rowData.text}</Text>
</View>
</TouchableHighlight>
)
}
render() {
return (
<View>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
automaticallyAdjustContentInsets={false} />
</View>
);
}
}
答案 0 :(得分:2)
我不知道您的Firebase数据库中有哪些数据,但据我所知,您应该为所有项目获取多个“on_child_added”事件,因此您不应将其传递给“cloneWithRows”方法。您应该将整个数据集传递给它。
虽然关于本机反应的文档目前关于ListView数据源如何工作以及应该传递给“cloneWithRows”的内容有点“沉默”,但代码中的文档(ListViewDataSource.js)实际上是非常好的,并且显而易见的是,您应该始终为“cloneWithRows”方法提供完整的数据集(类似于查看协调,数据源将自动计算差异并仅修改实际更改的数据)。
此外,@ vjeux对他们实现ListView的原因进行了非常好的解释,包括解释他们选择的优化策略(与iOS的UITableView不同)。
因此,在您的情况下,您应该在其他地方累积所有行,并且只将整个消息数组传递给cloneWithRows或者对cloneWithRows的增量行为进行中继,并将传入的元素连续追加到cloneWithRows,如下面的示例所示(它本来应该很快,所以试一试。)
来自ListViewDataSource.js的文档副本和粘贴:
/**
* Provides efficient data processing and access to the
* `ListView` component. A `ListViewDataSource` is created with functions for
* extracting data from the input blob, and comparing elements (with default
* implementations for convenience). The input blob can be as simple as an
* array of strings, or an object with rows nested inside section objects.
*
* To update the data in the datasource, use `cloneWithRows` (or
* `cloneWithRowsAndSections` if you care about sections). The data in the
* data source is immutable, so you can't modify it directly. The clone methods
* suck in the new data and compute a diff for each row so ListView knows
* whether to re-render it or not.
*
* In this example, a component receives data in chunks, handled by
* `_onDataArrived`, which concats the new data onto the old data and updates the
* data source. We use `concat` to create a new array - mutating `this._data`,
* e.g. with `this._data.push(newRowData)`, would be an error. `_rowHasChanged`
* understands the shape of the row data and knows how to efficiently compare
* it.
*
* ```
* getInitialState: function() {
* var ds = new ListViewDataSource({rowHasChanged: this._rowHasChanged});
* return {ds};
* },
* _onDataArrived(newData) {
* this._data = this._data.concat(newData);
* this.setState({
* ds: this.state.ds.cloneWithRows(this._data)
* });
* }
* ```
*/