我正在向返回一些电影的JSON文件提出AJAX请求。
state = { movies: [] };
componentWillMount()
{
this.getMovies();
}
/*
Make an ajax call and put the results in the movies array
*/
getMovies()
{
axios.get('https://pastebin.com/raw/FF6Vec6B')
.then(response => this.setState({ movies: response.data }));
}
/*
Render every movie as a button
*/
renderMovies()
{
const { navigate } = this.props.navigation;
return this.state.movies.map(movie =>
<ListItem key={ movie.title }
title={ movie.title }
icon={{ name: 'home' }}
onPress={() =>
navigate('Details', { title: movie.title, release: movie.releaseYear })
}
/>
);
}
render() {
return(
<List>
{ this.renderMovies() }
</List>
);
}
我得到的错误是:this.state.map不是函数。这是因为电影仍然是空的。
当我console.log响应data时,它会返回JSON文件中的所有行。因此,问题最有可能在此行中:
.then(response => this.setState({ movies: response.data }));
有人知道怎么了吗?
您将初始状态放在错误的位置。而是这样做:
constructor(props) {
super(props);
this.state = { movies: [] };
}
来自文档:
通常,您应该在构造函数中初始化
state
,然后 想更改时致电setState
。
更新AJAX请求如下:
/*
Make an ajax call and put the results in the movies array
*/
getMovies()
{
let self = this;
axios.get('https://pastebin.com/raw/FF6Vec6B')
.then(response => self.setState({ movies: response.data }));
}
另外,您可以在构造函数中绑定函数为:
constructor(props){
super(props);
this.getMovies = this.getMovies.bind(this);
}