next.js-getInitialProps在组件中不起作用

问题描述 投票:0回答:2

这是我的代码

import React from 'react'
import fetch from 'isomorphic-unfetch'
import Book from './Book'

function getNum(val) {
    val = +val || 0;
    return val;
}

class BookList extends React.Component {
    static async getInitialProps(ctx) {;
        const res = await fetch('/api/books');
        const json = await res.json();
        return { books: json }
    }

    render() {
        var books = this.props.books;

由于某种原因,渲染功能中的“书”未定义。为什么getInitialProps在组件中不起作用?

reactjs next.js
2个回答
0
投票

[getInitialProps只能添加到页面导出的默认组件,将其添加到任何其他组件将不起作用。


0
投票

[getInitialProps仅在页面级别有效,而在组件级别无效。

sgetInitialProps can not be used in children components, only in the default export of every page

https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#caveats

© www.soinside.com 2019 - 2024. All rights reserved.