React Native的新功能...我正在尝试调用一个函数,该函数在render()方法中的组件内执行获取请求。
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class Home extends React.Component {
static navigationOptions = {
title: 'Details',
};
getMoviesFromApiAsync = () => {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
};
render() {
return (
<React.Fragment>
<Text>{getMoviesFromApiAsync()}</Text>
</React.Fragment>
);
}
}
但是,我收到了ReferenceError:找不到变量getMoviesFromApiAsync()。为什么会这样?
答案 0 :(得分:1)
您需要在您的类上调用方法,这是Vanilla Javascript的基本功能。
<Text>{this.getMoviesFromApiAsync()}</Text>
但是,这里的方法不好,您应该写出组件以将api请求的结果存储为组件状态。这样,您无需在每个渲染周期都发出请求!
export default class Home extends React.Component {
static navigationOptions = {
title: 'Details',
};
state = {
movies: []
}
componentDidMount() {
this.getMoviesFromApiAsync()
}
getMoviesFromApiAsync = () => {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
movies: [...this.state.movies, ...responseJson.movies]
})
})
.catch((error) => {
console.error(error);
});
};
render() {
const { movies } = this.state
return (
<React.Fragment>
{ movies.map( (movie, i) => <Text>{movie.title}</Text> ) }
</React.Fragment>
);
}
}