Next.js:重新加载页面时获取数据

4

在React中,当重新加载页面时,我们使用useEffect来获取数据:

useEffect(() => {
  let ignore = false
  const fetchingData = async () => {
    const res = await fetch(<your_path>)
    const data = await res.json()
    if (!ignore) setData(data)
  }; 
  fetchingData()
  return () => { ignore = true }
}, [])

但是在 Next.js 中,我该如何做到这一点呢?当页面重新加载时,在 getInitialProps 中使用 Fetch 无法触发。


1
你的问题就是我的答案,谢谢。 - Fatemeh Qasemkhani
@FatemehQasemkhani,我的问题是基于我的next.js能力不足,后来我意识到问题出在getInitialProps中的axios请求。很高兴能提供帮助!:) - Arthur
2个回答

2

使用axios或isomorphic-unfetch。它们在客户端和服务器环境中都可以工作。Fetch API在Node.js环境中不存在。如果你仍然想在客户端代码中使用Fetch API,你应该使用isomorphic-unfetch。当你在浏览器中时,它使用unfetch polyfill。如果你的代码在Node.js中运行,它会切换到node-fetch。

import "axios" from "axios"

static async getInitialProps(){
    const res=await axios.get('url')//
    const data=res.data
    return {data}
}

更新

除了客户端的fetch()之外,Next.js在Node.js环境中也使用polyfill对fetch()进行填充。您可以在服务器代码(例如getStaticProps/getServerSideProps)中使用fetch(),而无需使用isomorphic-unfetch或node-fetch等polyfill。

https://nextjs.org/docs/basic-features/supported-browsers-features


我不确定更新是什么时候进行的,但在撰写此评论时,Next已经为fetch提供了一个polyfill,可在客户端和服务器上使用。 - dkapur17
@dkapur17,你说得对。我需要更新答案。 - Yilmaz

1
Next.js 中,通常会在 getInitialProps 中使用 HTTP 请求加载数据,然后您可以将它们用作 props。
const App = props => (
  <Layout>
  {props.data}
    ...
  </Layout>
);

App.getInitialProps = async function() {
  const res = await fetch(<your_path>)
  const data = await res.json()
  return {
   data
  }
};

export default App;

似乎它只在路由更改时起作用,而不是在页面刷新时。 - Arthur
1
当您刷新页面时,应仍调用getInitialProps。您的问题的目的是找到何时/何处进行fetch调用并更新props。我给出了标准答案:使用getInitialProps。但如果您需要在组件而非页面中进行此调用,请使用componentDidMount。 - Melchia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接