首页 > 解决方案 > Next.js - 页面没有让 GetServerSideProps 进入页面组件道具(使用自定义 _app.js)

问题描述

我一直在尝试添加GetServerSideProps到我的 Next.js 应用程序,但是在尝试这样做时,响应数据没有被注入到页面道具中。当查看网络选项卡时,我看到pageName.json生成,因此正在执行调用并获取数据,它只是没有作为道具进入页面。

这是我的页面 component.ts

import { useState } from "react";
import { url } from "../app/helpers/api/apiEnvs";
import { Button, Spin, Skeleton } from "antd";
import { MailOutlined, LoadingOutlined } from '@ant-design/icons';
import withLayout from "../app/components/Layout";
import './quotes.scss'

export const getServerSideProps = async (ctx) => {
const res = await fetch(`${url}/estimator/start`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
        });
    const estimator = await res.json();
    return {
        props: { estimator }
    };
};


const Quotes = (props: any) => {

    const [loading, setLoading] = useState(false);
    const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

    return (
        <div className="quotesContainer">
            <h1>Cotizador</h1>
            <div className="quoteBox quoteStepper">
            <MailOutlined/>
            </div>
            <div className="quoteBox quoteContent">
            {loading
                ? <Spin indicator={antIcon} />
            : <div>
                    <Skeleton.Input style={{ width: '300px' }} active={true} size="large" />
                    <p>{props.estimation ? props.estimation: 'No estimation'}</p>

                    <Skeleton.Button style={{ width: '90px' }} active={true} size="default" />
                    <Button type="primary">
                        Next
                    </Button>
              </div>
            }
            </div>
        </div>
    );
};

export default withLayout(Quotes);

自定义 _app.js 组件

import 'antd/dist/antd.css';

export default function App({ Component, pageProps }) {
    return <Component {...pageProps} />
}

网络选项卡中显示的数据的屏幕截图

可能与拥有 ts 页面和 .js _app 有关吗?

标签: javascriptnext.js

解决方案


_app.js可能有你必须调用的习惯getInitialProps。需要进行一些修改

static async getInitialProps({ Component, ctx }) {
     const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};

    if (Object.keys(pageProps).length > 0) {
      // return pageProps only when its present
      return { pageProps }; 
    
    }
    return {};
  }

pageProps是的,只有当它存在时,您才必须返回。


推荐阅读