Nextjs 重新加载页面时获取数据

Nextjs Fetch data when reloading the page

在 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。

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;

使用 axios 或 isomorphic-unfetch。它们在客户端和服务器环境中都可以工作。 Node.js 环境中不存在 Fetch API。它。如果您仍想在客户端代码中使用 Fetch API,则应使用同构取消获取。当您在浏览器中时,它会使用 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 polyfills fetch() 在 Node.js 环境中。您可以在您的服务器代码(例如 getStaticProps/getServerSideProps)中使用 fetch() 而无需使用诸如 isomorphic-unfetch 或 node-fetch.

的 polyfill

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