我有以下组件,我试图从API中检索电影列表。但是,变量movies
不包含预期结果。
我做错了什么?
以下是代码:
import React, { Component, } from 'react'
import { View } from 'react-native'
import {
List,
ListItem,
Text,
} from 'native-base';
class Test extends Component {
render() {
var movies = this.getMoviesFromApi();
for(var movie in movies)
{
console.warn(movie);
}
return (
<List dataArray={movies}
renderRow={(movie) =>
<ListItem>
<Text>{movie}</Text>
</ListItem>}
/>
);
}
async getMoviesFromApi() {
try {
let response = await fetch('https://facebook.github.io/react-native/movies.json');
let responseJson = await response.json();
return responseJson.movies;
} catch(error) {
console.error(error);
}
}
}
export default Test;
答案 0 :(得分:2)
在您的提取通话中,您应该通过then()
电话返回回复。这是我写的应用程序的一个例子:
// inside Utils/api.js
getAllSchools(accessToken){
var url = `${baseUrl}/schools`
return fetch(url).then((res) => res.json())
.catch((e) => {
console.log('an error occurred getting schools', e)
api.logError(e.message);
})
},
然后,无论你在何处调用你的函数,都要将电影设置为该响应:
api.getAllSchools("klsafj").then((res) => {
var movies = res.data
// then do whatever else you want to do with movies
// or you could set movies to a state and use elsewhere
})
希望这有帮助。