【问题标题】:calling api does not work nextjs getinitialprops调用 api 不起作用 nextjs getinitialprops
【发布时间】:2021-08-04 15:35:12
【问题描述】:

我想用下一个 getinitialprops 和 axios 从 api 获取一些数据

虽然我在这里添加的代码是getInitialProps,但它不起作用

文件的路径是pages/index.tsx

IndexPage.getInitialProps = async (ctx: any) => {
  try {
    const res = await axios.get(
      "THE_PATH"
    );
    const restaurants = res.data;
    return { restaurants };
  } catch (error) {
    return { error };
  }
};

这是我尝试使用它的方式

const IndexPage = (props: any) => {

 <div
      onClick={() => {console.log(props)}}>

它不显示道具

我错过了什么

【问题讨论】:

    标签: typescript axios next.js


    【解决方案1】:

    您需要将对象作为props 的值返回,而不是返回{restaurant };

    return {
        props: { restaurant }, // will be passed to the page component as props
    }
    

    props - 一个必需的对象,其中包含将由 页面组件。

    参考

    https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

    https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering

    【讨论】:

    • 我正在使用getInitalProps 我按照您的回答但仍然无法正常工作,有什么建议吗?
    • @josephsmith 是 res.data 拥有正确的数据吗?
    • 是的 res 是 axios 对象,其中包含数据状态等......它可能是 axios 的下一个问题,还是我应该在发出请求之前配置任何东西?因为当我将一个虚拟对象传递给它时,它可以工作,而且如果我单独提出请求,它也可以工作
    • 还是因为我试图在 pages 目录的 index.js 中使用 getInitialProps?
    • 或者 api 本身不支持服务器端渲染导致请求失败?因为当我向 jsonplaceholder 发出请求时,它工作正常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 2020-07-13
    • 1970-01-01
    • 2020-06-26
    • 2021-06-23
    • 2020-02-12
    • 2018-01-05
    相关资源
    最近更新 更多