[英]How to add newly fetched items to the top of the list in react native?
In my project I'm fetching json
data from server and list within a card
.But the problem I'm facing is whenever a new item is added to json data
new item will be rendered at the bottom of the existing card
.But what I want is it should be populated at the top of existing cards
.So how do I do that?Following is my sample code for fetch and listing cards.Please help me to find a solution.Any help would be really appreciable.Thank you.在我的项目中,我从服务器和
card
列表中获取json
数据。但我面临的问题是每当向json data
添加新项目时,新项目将呈现在现有card
的底部。但是我所面临的问题想要它应该填充在现有cards
的顶部。那么我该怎么做?以下是我的获取和列出卡片的示例代码。请帮助我找到解决方案。任何帮助都将非常值得赞赏。谢谢。
componentWillMount(){
fetch(GLOBAL.NEW_WORK_REQUEST,{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
name:"name"
})
})
.then((response) => response.json())
.then((responseData) =>
{
this.setState({
work_rq :responseData.data
})
});
}
}
...
...
<View>
{this.state.work_rq.map(a => (
<CardSection>
<TouchableOpacity>
<Text style={{fontSize:18,padding:8}}>Work Category:{a.work_type}</Text>
</TouchableOpacity>
</CardSection>
))}
</View>
You can this using two ways您可以使用两种方式
1) use array.reverse()
, two arrays will not be used. 1) 使用
array.reverse()
,不会使用两个数组。
2) use two arrays 2nd array will be used when you add new data here I am using 2 states newdata
and data
where newdata
is on the top of the 2)使用两个数组当你在这里添加新数据时将使用第二个数组我使用2个状态
newdata
和data
,其中newdata
位于顶部
like this, (2nd approach)像这样,(第二种方法)
constructor(props) {
super(props);
this.state = { data: [1, 2, 3], newData: [] };
}
handleClick() {
var data = Math.random();
this.setState({ newData: this.state.newData.concat(data) });
}
render() {
console.log(this.state);
return (
<div>
{this.state.newData && this.state.newData.reverse().map(a => {
return <div>{a}</div>
})}
{this.state.data.map(a => {
return <div>{a}</div>
})}
<button
className={this.state.isToggleOn ? 'ON' : 'OFF'}
onClick={(e) => this.handleClick(e)}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
</div>
);
}
1st approach you can simple do array.reverse and all data will be appended in reverse()第一种方法你可以简单地做 array.reverse 并且所有数据都将附加到 reverse()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.