【问题标题】:Not able to return data from getInitialProps() of lower order page component无法从低阶页面组件的 getInitialProps() 返回数据
【发布时间】:2019-04-20 10:04:26
【问题描述】:

我有一个低阶页面组件,它需要在 getInitialProps() 中获取数据。它成功地获取了数据,但它确实作为组件中的 prop 返回。 下面是我正在处理的代码

import React, { Component } from 'react';

import DefaultPage from '../hocs/DefaultPage';
import PageLayout from '../components/PageLayout';
import { getJwtFromLocalCookie, getJwtFromServerCookie } from '../utils/auth';

import { getUser } from '../services/users';

class Profile extends Component {
    static async getInitialProps(ctx) {
        let user;
        const jwt = process.browser ? getJwtFromLocalCookie() : getJwtFromServerCookie(ctx.req);
        try {
            const {data} = await getUser(ctx.query.id, jwt);
            user = data;
        }
        catch (err) {
            if(err.code === 404)
                ctx.res.statusCode = 404;
        }
        console.log(user);
        return { user };
    }

    constructor(props) {
        super(props);
        this.state = { user: null };
    }

    render() {
        console.log(this.props);
        return (
            <PageLayout
                active="" 
                loggedUser={this.props.loggedUser}
            >

            </PageLayout>
        );
    }
}

export default DefaultPage(Profile);

getInitialProps() 中的 console.log() 确实显示了正确的数据,但 render() 中的 console.log() 没有 user 属性。

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    好的,我找到了解决方案,结果在高阶组件的 getInitialProps() 中,低阶组件的 getInitialProps() 返回了一个承诺,需要处理

    所以,下面是我的 hoc getInitialProps 之前的代码

    static getInitialProps (ctx) {
        const loggedUser = process.browser ? getUserFromLocalCookie() : getUserFromServerCookie(ctx.req)
        const pageProps = Page.getInitialProps && Page.getInitialProps(ctx);
        return {
          ...pageProps,
          loggedUser,
          currentUrl: ctx.pathname,
          isAuthenticated: !!loggedUser
        }
      }
    

    以下是更正的代码

    static async getInitialProps (ctx) {
        const loggedUser = process.browser ? getUserFromLocalCookie() : getUserFromServerCookie(ctx.req)
        const pageProps = await (Page.getInitialProps && Page.getInitialProps(ctx));
        return {
          ...pageProps,
          loggedUser,
          currentUrl: ctx.pathname,
          isAuthenticated: !!loggedUser
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多