简体   繁体   English

如何在next.js的客户端上重新获取api数据?

[英]How to refetch api data on client side in next.js?

I need to reload the data from api once state changed. 状态更改后,我需要从api重新加载数据。 Is is possible to fetch data again with getInitialProps on client side? 是否可以在客户端使用getInitialProps再次获取数据?

Why don't you fetch the data on the componentDidMount? 您为什么不获取componentDidMount上的数据?

componentDidMount() {
  yourAPI.fetch().then((pFetchData) => {
    this.setState({data: pFetchData});
  });
}

In practice, componentDidMount is the best place to put calls to fetch data, for two reasons: 实际上,出于两个原因,componentDidMount是发出调用以获取数据的最佳位置:

  1. Using DidMount makes it clear that data won't be loaded until after the initial render. 使用DidMount可以清楚地表明,只有在初始渲染之后才会加载数据。 This reminds you to set up initial state properly, so you don't end up with undefined state that causes errors. 这提醒您正确设置初始状态,因此您不会因未定义状态而导致错误。
  2. If you ever need to render your app on the server (SSR/isomorphic/other buzzwords), componentWillMount will actually be called twice “ once on the server, and again on the client “ which is probably not what you want. 如果您需要在服务器上呈现您的应用程序(SSR /同构/其他流行语),componentWillMount实际上将被两次调用“一次在服务器上,一次在客户端”,这可能不是您想要的。 Putting the data loading code in componentDidMount will ensure that data is only fetched from the client. 将数据加载代码放入componentDidMount中将确保仅从客户端获取数据。

https://www.codeproject.com/Articles/1177776/Where-to-Fetch-Data-componentWillMount-vs-componen https://www.codeproject.com/Articles/1177776/Where-to-Fetch-Data-componentWillMount-vs-componen

Hope it helps :) 希望能帮助到你 :)

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

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