我们如何在行之前添加行到本机列表视图? [英] How can we prepend rows to a react native list-view?
问题描述
我几乎到处都在寻找解决方案!
I've looked almost everywhere to find a solution to this!
有没有一种方法可以将行添加到 listview
而不重新渲染每一行?我觉得奇怪的是, facebook
在文档中没有包含执行此操作的方法!我觉得好像有一种内存有效的方式可以做到这一点,就像使用本机脚本(java,swift)一样.
Is there a way of prepending rows to a listview
without re-rendering every single row? I find it bizarre that facebook
haven't included a way to do this in there documentation! I feel as though there could be a memory efficient way of doing this as you can do it with the native scripts (java, swift).
有很多讨论试图解决它,例如:
There are a lot of discussions that try to solve it, such as this one:
https://github.com/facebook/react-native/issues/1682
但是到目前为止,我还没有找到一种有效的方法.
But as of yet I haven't found an efficient way of doing this.
推荐答案
没有直接方法可以将行添加到ListView中.ListView.DataSource上没有太多文档.所以就到了-
There is no direct method to prepend rows to your ListView. There is not much documentation on ListView.DataSource out there. So here it goes-
如果要从ListView添加/追加/添加/添加/更新/删除行,您要做的就是更新dataSource并在setState中调用cloneWithRows().
If you want to add/append/prepend/update/delete rows from a ListView, all you have to do is just update the dataSource and call cloneWithRows() in setState.
例如我想从URL提取数据.每次我点击加载更多"时,都会向数据源添加新行.
For eg. I want to fetch data from a URL. Each time I hit "Load more", I append new rows to my data source.
getInitialState: function(){
return {
rawData: [],
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
}),
loaded: false,
page: 1,
}
},
我第一次在ComponentDidMount()中调用此函数,该函数以初始数据和状态中的"page" = 1填充我的ListView.
At the very first time, I call this function in ComponentDidMount() which populates my ListView with initial data and "page"=1 in the state.
reloadData: function(){
this.setState({ loaded: false, rawData: [], page: 1 });
API.getUpcomingMovies(this.state.page)
.then((data) => {
this.setState({
rawData: this.state.rawData.concat(data),
dataSource: this.state.dataSource.cloneWithRows(this.state.rawData.concat(data)),
loaded: true,
});
});
},
每当我点击加载更多"以从API获取JSON时,我都会调用以下函数.每当我点击加载更多"时,网页"就会增加.
And every time I tap on "load more" to get JSON from the API, I call the following function. Where "page" is incremented every time I hit "load more".
fetchData: function(){
this.setState({ loaded: false, page: this.state.page+1 });
API.getUpcomingMovies(this.state.page)
.then((data) => {
this.setState({
rawData: this.state.rawData.concat(data),
dataSource: this.state.dataSource.cloneWithRows(this.state.rawData.concat(data)),
loaded: true,
});
});
},
如您所见,我正在串联我的rawData [](这是一个保存JSON对象的简单数组).如果要在rawData之前添加新数据,则可以执行以下操作-
As you can see, I am concatenating my rawData[] (which is a simple array holding JSON objects). If you want to prepend new data to your rawData, you can do something like this-
this.setState({
rawData: data.concat(this.state.rawData)
)}
这篇关于我们如何在行之前添加行到本机列表视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!