【问题标题】:Next.js import fetch data from child component to parent page in ReactNext.js 将子组件中的数据导入到 React 中的父页面
【发布时间】:2019-11-10 16:31:47
【问题描述】:

我正在使用 Next.js 将我的 CRA 转换为 SSR 应用程序。我刚刚开始并且已经遇到了一个简单的问题(我希望)。我可以使用 getInitialProps() 直接从我的 index.js 页面将数据呈现给浏览器。我显然不想在我的索引页面上设置我的整个应用程序。

我遇到的问题是尝试将数据从子组件导入索引页面。使用与我的工作示例相同的代码,我得到了可怕的“TypeError:无法读取未定义的属性'map'”错误。这种简单的导出/导入设置在 React 中不可行吗?

这是一个类似于我的代码的示例,在子组件中...

import Link from 'next/link'
import 'isomorphic-unfetch'

export default class Index extends React.Component {
  static async getInitialProps () {
    // eslint-disable-next-line no-undef
    const res = await fetch('https://api.github.com/repos/zeit/next.js')
    const json = await res.json()
    return { stars: json.stargazers_count }
  }

  render () {
    return (
      <div>
        <p>Next.js has {this.props.stars} ⭐️</p>
        <Link prefetch href='/preact'>
          <a>How about preact?</a>
        </Link>
      </div>
    )
  }
}

然后我将该组件导入到我的索引中...

import React from 'react'
import App from '../components/App.js';

export default class Index extends React.Component {

  render () {
    return (
      <div>
         <App />
      </div>
    )
  }
}

同样,子组件作为独立的父组件工作,而不是作为子组件。获取错误 .map 未定义。

【问题讨论】:

  • 看起来 getInitialProps 在子组件中不起作用...从子组件进行 SSR 调用的正确方法是什么?这个答案可能已经在谷歌机器上,但是找不到直接答案。
  • 一开始为什么要在 SSR 期间获取远程数据?您真正需要的只是初始渲染的基本页面结构,您可以使用钩子或传统的生命周期方法很好地在客户端填充数据。你不应该在这里使用getInitialProps

标签: javascript reactjs fetch next.js


【解决方案1】:

来自 Next.js 文档:

注意:getInitialProps 不能用于子组件。仅在页面中。

【讨论】:

  • 是的,我在发布问题后注意到了这一点。我现在正在尝试找出更高阶的组件解决方案。
猜你喜欢
  • 2020-05-25
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2022-06-30
  • 1970-01-01
  • 2021-06-10
  • 2020-03-15
相关资源
最近更新 更多