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.
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.
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
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()
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.