getInitialProps 不适用于异步函数
getInitialProps does not work with async function
我在此路径中有文件 ./pages/blog/[id]/[title].js
,这是我编写的代码:
import React from 'react';
import PropTypes from 'prop-types';
import fetch from 'isomorphic-unfetch';
import BASE_URL from '../../../BaseURL';
const BlogSinglePage = props => {
console.log(props.post);//undefined
console.log(props);//{}
return (
<div></div>
);
};
BlogSinglePage.propTypes = {
post: PropTypes.object
};
BlogSinglePage.getInitialProps = async ({ query }) => {
const res = await fetch(`${BASE_URL}/api/post/${query.id}`);
const post = await res.json();
return { post };
};
export default BlogSinglePage;
我的问题是,当 getInitialProps
是一个 async
函数时,BlogSinglePage
的属性是空的,但只要 getInitialProps
不是 async
函数,一切正常,道具不为空
我已逐行执行 Implement the Post Page 中的代码,但它对我不起作用
我不知道为什么会出现这个问题,
但我用 next-cli
重新安装了下一个 js,问题就解决了:)
我在此路径中有文件 ./pages/blog/[id]/[title].js
,这是我编写的代码:
import React from 'react';
import PropTypes from 'prop-types';
import fetch from 'isomorphic-unfetch';
import BASE_URL from '../../../BaseURL';
const BlogSinglePage = props => {
console.log(props.post);//undefined
console.log(props);//{}
return (
<div></div>
);
};
BlogSinglePage.propTypes = {
post: PropTypes.object
};
BlogSinglePage.getInitialProps = async ({ query }) => {
const res = await fetch(`${BASE_URL}/api/post/${query.id}`);
const post = await res.json();
return { post };
};
export default BlogSinglePage;
我的问题是,当 getInitialProps
是一个 async
函数时,BlogSinglePage
的属性是空的,但只要 getInitialProps
不是 async
函数,一切正常,道具不为空
我已逐行执行 Implement the Post Page 中的代码,但它对我不起作用
我不知道为什么会出现这个问题,
但我用 next-cli
重新安装了下一个 js,问题就解决了:)