版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AmazingUU/article/details/77543360
前面的文章React Native利用ScrollableTabView实现Tab+ViewPager效果里面的item内容都是写死的,这篇文章将其改进一下,改成从服务端获取Json数据并在FlatList里显示出来。
由于是简单的实现一下,就采用官方提供的例子里面的url(https://facebook.github.io/react-native/movies.json)
{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "title": "Star Wars", "releaseYear": "1977"},
{ "title": "Back to the Future", "releaseYear": "1985"},
{ "title": "The Matrix", "releaseYear": "1999"},
{ "title": "Inception", "releaseYear": "2010"},
{ "title": "Interstellar", "releaseYear": "2014"}
]
}
1、fetch获取Json数据
fetchData(){
var url = 'https://facebook.github.io/react-native/movies.json';
fetch(url)
.then((res)=> res.json())
.then((json)=>{
this.setState({resultJson:json});//将json数据传递出去,setState会重新调用render()
})
.catch((e)=>{
alert(e);
});
}
2、在生命周期回调函数里调用fetch
//在最初的render方法调用之后立即调用。
//网络请求、事件订阅等操作可以在这个方法中调用。
//作用相同与Fragment生命周期中的onViewCreate方法。
componentDidMount(){
this.fetchData();
}
3、将Json数据传递给render里
这里的关键代码也就是第一步里的setState,将json数据传递给state
//构造函数时在state里设一个resultJson,用来接收fetch传出来的Json数据
constructor(props){
super(props);
this.state={
resultJson:null
};
}
。。。
this.setState({resultJson:json});//setState会重新调用render()
4、在render里将数据显示出来
在这一步遇到了些问题,一开始的代码如下:
。。。
dataSource1 = {
tab:'Movies',
list:[
{key: this.state.resultJson.movies[0].title,index:'0'},
{key: this.state.resultJson.movies[1].title,index:'1'},
{key: this.state.resultJson.movies[2].title,index:'2'},
{key: this.state.resultJson.movies[3].title,index:'3'},
]
}
。。。
前后的代码我就不贴了,前面的文章有,这段代码是在render函数里的最前面。这里的dataSource1 就是Tab1的标签和数据,运行一下会报错:
意思是movies是null,但是我在fetch函数里打印一下,确实是有数据的。通过查找资料,发现React Native的生命周期,是先render,再componentDidMount,里面的setState之后又会重新调用render。这里出错的原因就是最开始调用render的时候,movies并没有数据,要等fetch之后才有数据。将代码改成下面的就可以了
var dataSource1 = null;
if (!this.state.resultJson) {
dataSource1 = {
tab:'Tab1',
list:[
{key: 'Loading...',index:'0'},
{key: 'Loading...',index:'1'},
{key: 'Loading...',index:'2'},
{key: 'Loading...',index:'3'},
]
}
}else{
dataSource1 = {
tab:'Movies',
list:[
{key: this.state.resultJson.movies[0].title,index:'0'},
{key: this.state.resultJson.movies[1].title,index:'1'},
{key: this.state.resultJson.movies[2].title,index:'2'},
{key: this.state.resultJson.movies[3].title,index:'3'},
]
}
}
最开始调用render的时候,resultJson的数据为空,会显示Loading。。。。等到fetchData函数里的setState调用之后,又会重新调用render,这时候resultJson就有数据了,就可以显示出来了。
关于React Native生命周期参考下面的资料
https://race604.com/react-native-component-lifecycle/
效果图:
解决问题参考的资料: