简体   繁体   English

反应:为什么状态要正确更新到第二次?

[英]React: why the state is updated correctly until the second time?

I'm fetching data (pics and descriptions) from server, and using them in infinite scroll. 我正在从服务器获取数据(图片和描述),并在无限滚动中使用它们。 When I'm scroll to bottom of page I want to change state value (value of the page from which we collect data). 当我滚动到页面底部时,我想更改状态值(我们从中收集数据的页面的值)。

When I'm doing this, something goes wrong. 当我这样做时,出现了问题。 State update correctly only on second and each next time. 状态仅在第二次和下一次正确更新。

Code: 码:

class Gallery extends Component {
  state = {
    photos: [],
    searchValue: "dog",
    page: 1,
    totalPages: null
  };

  getPhotos = () => {
    const { photos, searchValue, page, totalPages } = this.state;

    axios.get(`api_key=${API_KEY}&tags=${searchValue}&page=${page}`)
      .then(res => {
        this.setState({
          photos: [...photos, ...res.data.photos.photo],
          totalPages: res.data.photos.pages
        });
        if (page < totalPages) {
          this.setState(prevState => ({ page: prevState.page + 1 }));
          console.log(page); // returns 1 on the first call, but should return 2;
        }
      })
  };

  render() {
    const { photos, page, totalPages, loading } = this.state;

    return (
      <div className={classes.Content}>
        <InfiniteScroll
          pageStart={page}
          loadMore={this.getPhotos}
          hasMore={page < totalPages}
          loader={<Spinner />}
        >
          <Photos photos={photos} />
        </InfiniteScroll>
      </div>
    );
  }
}

and now, the problem is here: 现在,问题出在这里:

if (page < totalPages) {
    this.setState(prevState => ({ page: prevState.page + 1 }));
}

on the first function call, page is 1, but on my logic should be 2. On the next calls everything work good (page is 2, 3, 4 etc.). 在第一个函数调用中,page为1,但在我的逻辑上应该为2。在下一个调用中,一切正常(页面为2、3、4等)。 For now i'm loading two times the same photos. 目前,我正在加载两次相同的照片。 Can You help me? 你能帮助我吗?

As we know setState in react is asynchronous so you can't see the value immediately when modified. 我们知道react中的setState是异步的,因此修改后无法立即看到该值。

To get the updated value you should do something like below 要获取更新的值,您应该执行以下操作

 getPhotos = () => {
      const { photos, searchValue, page, totalPages } = this.state;
    if (page < totalPages) {
          this.setState(prevState => ({ 
              page: prevState.page + 1 
          }), () => {
               console.log(this.state.page);//will print 2
             axios.get(`api_key=${API_KEY}&tags=${searchValue}&page=${this.state.page}`)
        .then(res => {
           this.setState({
              photos: [...photos, ...res.data.photos.photo],
              totalPages: res.data.photos.pages
          });
        })
      });
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM