gpt4 book ai didi

javascript - React Native 状态没有改变

转载 作者:行者123 更新时间:2023-11-28 10:43:43 26 4
gpt4 key购买 nike

我正在向返回一些电影的 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 response.data 时,它返回 JSON 文件中的所有行。所以问题很可能出在这一行:

.then(response => this.setState({ movies: response.data }));

有人知道出了什么问题吗?

最佳答案

您将初始状态放在了错误的位置。改为这样做:

constructor(props) {
super(props);
this.state = { movies: [] };
}

来自document :

In general, you should initialize state in the constructor, and then call setState when you want to change it.

关于javascript - React Native 状态没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com