首页 > 解决方案 > 反应状态按钮点击落后

问题描述

我查看了其他解决方案,但似乎无法将它们合并到我自己的代码中。

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}&region=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);
      }

标签: reactjsreduxreact-reduxstate

解决方案


setState由于是异步的,您总是看到落后 1 的状态。

在这段代码中:

<PaginationLink previous href="#toggle-buttons" onClick={()=>
{this.handleMovieClick('-'); this.handleFetchNewMovie(this.props.apiKey, this.state.moviePage)}} />

handleMovieClick发生了,但还不this.state.moviePage是下一页。

另外需要注意的是,当反应状态更新依赖于先前的状态时,您应该将一个函数传递给setState接收先前状态的函数。由于setState. 设置状态文档


推荐阅读