reactjs - 反应状态按钮点击落后
问题描述
我查看了其他解决方案,但似乎无法将它们合并到我自己的代码中。
handleMovieClick = pageTransition => {
if (this.state.moviePage === 1 && pageTransition === '-') {
this.setState({ moviePage: 1 });
} else if (pageTransition === '+') {
this.setState({ moviePage: this.state.moviePage + 1 })
} else if (pageTransition === '-') {
this.setState({ moviePage: this.state.moviePage - 1 })
}
}
上面是后面1的setState,例如,我必须点击两次才能到达1。我知道这与我的状态渲染一次点击然后状态增加有关,但我不知道如何修理它。任何帮助,将不胜感激。
this.state = {
moviePage: 1,
tvPage: 1
};
下面是电影触发器
<PaginationLink previous href="#toggle-buttons" onClick={()=>
{this.handleMovieClick('-'); this.handleFetchNewMovie(this.props.apiKey, this.state.moviePage)}} />
这是一个异步调用,可能是状态落后 1 步的原因?
handleFetchNewMovie = (apiKey, page = 1) => {
this.props.postMoviePopular(`https://api.themoviedb.org/3/movie/popular?api_key=${apiKey}&language=en-US&page=${page}®ion=US`);
}
componentDidMount() {
this.props.postMDBConfig(`https://api.themoviedb.org/3/configuration?api_key=${this.props.apiKey}`);
this.handleFetchNewMovie(this.props.apiKey);
this.handleFetchNewTV(this.props.apiKey);
}
解决方案
setState
由于是异步的,您总是看到落后 1 的状态。
在这段代码中:
<PaginationLink previous href="#toggle-buttons" onClick={()=>
{this.handleMovieClick('-'); this.handleFetchNewMovie(this.props.apiKey, this.state.moviePage)}} />
handleMovieClick
发生了,但还不this.state.moviePage
是下一页。
另外需要注意的是,当反应状态更新依赖于先前的状态时,您应该将一个函数传递给setState
接收先前状态的函数。由于setState
. 设置状态文档
推荐阅读
- python - tf.keras 两个损失,中间层作为其中一个的输入错误:急切执行函数的输入不能是 Keras 符号张量
- unit-testing - 如何模拟这些类型的查询?
- sql - 如何在生产中修改数据库模式
- sql - 在 SQL Server 中将月份名称转换为月份编号
- for-loop - 如何将for循环中的图像名称更改为特定数字
- c++ - 使用容器提升 X3 解析结构
- c - 如何将文件中的信息存储到C中的内存中
- boolean - 大型布尔表达式的替换
- c - 如何使用 malloc 和 realloc 使用 C 分配字符串
- python - 如何为发布配置不同的请求正文并在 django-rest-framework 中对同一端点进行调用