[英]Not able to return data from getInitialProps() of lower order page component
I have a lower order page component that needs to fetch data in the getInitialProps(). 我有一个低阶页面组件,需要在getInitialProps()中获取数据。 It successfully fetches the data, but it does return as prop in the component. 它成功获取了数据,但在组件中确实作为prop返回。 Below is the code I'm working on 以下是我正在处理的代码
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);
The console.log() in the getInitialProps() does display the correct data, but the console.log() in render() doesn't have the user prop. getInitialProps()中的console.log()确实显示正确的数据,但是render()中的console.log()没有用户属性。
Ok, I found the solution, turns out in the getInitialProps() of the higher order component the getInitialProps() of the lower order component was returning a promise and needed to be handled 好的,我找到了解决方案,结果在高阶组件的getInitialProps()中,低阶组件的getInitialProps()返回了一个promise,需要处理
So, below is the before code of my hoc getInitialProps 因此,以下是我的特殊getInitialProps的before代码
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
}
}
And the following is corrected code 而以下是更正的代码
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.