反应| NextJS:不能使用getInitialProps()返回的道具

时间:2020-07-03 11:31:26

标签: reactjs next.js server-side-rendering

我第一次尝试使用NextJS进行SSR,但无法访问从getInitialProps()返回的道具:

错误: TypeError:无法读取未定义的属性“地图”

index.js:

import React from 'react';
import axios from 'axios';

const Index = ({ posts }) => {
    return (
        <div>
            <h1>Our Index Page!</h1>
            <ul>
                {posts.map(post => (
                    <li key={post.id}>post.title</li>
                ))}
            </ul>
        </div>
    );
}
Index.getInitialProps = async (ctx) => {
    const url = 'http://jsonplaceholder.typicode.com/posts';
    const res = await axios.get(url);
    const { data } = res;
    return { posts: data } // this returns data as posts in the props to the component
};

export default Index;

如果您想查看 _app.js

import React from 'react'
import App from 'next/app'
import Navbar from '../components/Navbar';

class MyApp extends App {
    static async getInitialProps({ Component, ctx }) {
        let pageProps = {};

        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx);
        }

        return { pageProps };
    }
    render() {
        const { Component, pageProps } = this.props;

        return (
            <div>
                <Navbar />
                <Component {...pageProps} />
            </div>
        )
    }
}

export default MyApp; 

可以肯定我缺少什么。预先感谢。

1 个答案:

答案 0 :(得分:0)

在我的设置中,它运行良好,例如,我只能模拟类型为null的指针错误。不等待axios的回应,请。检查以下内容:


       return await axios.get(url).then((res) => {console.log(res.status);
          console.log(res.config);
          console.log(res.headers);
          console.log(res.data);
          return { posts: res.data }
        }).catch((e) => {
          console.log('error: ', e)
        })