gpt4 book ai didi

javascript - 无法从低阶页面组件的 getInitialProps() 返回数据

转载 作者:行者123 更新时间:2023-12-03 00:43:12 41 4
gpt4 key购买 nike

我有一个低阶页面组件,需要在 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 属性。

最佳答案

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

所以,下面是我的 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
}
}

关于javascript - 无法从低阶页面组件的 getInitialProps() 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53351031/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com