[英]Can't return props from getInitialProps when in custom error page
[英]Not able to return data from getInitialProps() of lower order page component
我有一個低階頁面組件,需要在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()沒有用戶屬性。
好的,我找到了解決方案,結果在高階組件的getInitialProps()中,低階組件的getInitialProps()返回了一個promise,需要處理
因此,以下是我的特殊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
}
}
而以下是更正的代碼
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.