Next.js 在 React 中从子组件导入获取数据到父页面
Next.js import fetch data from child component to parent page in React
我正在使用 Next.js 将我的 CRA 转换为 SSR 应用程序。我刚刚开始并且已经 运行 解决了一个简单的问题(我希望如此)。我可以使用 getInitialProps() 直接从我的 index.js 页面向浏览器呈现数据。我显然不想在我的索引页面上设置我的整个应用程序。
我遇到的问题是尝试将数据从子组件导入到索引页。使用与我的工作示例相同的代码,我得到了可怕的 "TypeError: Cannot read property 'map' of undefined" 错误。这个简单的 export/import 设置在 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 is not defined.
来自 Next.js 文档:
Note: getInitialProps can not be used in children components. Only in pages.
我正在使用 Next.js 将我的 CRA 转换为 SSR 应用程序。我刚刚开始并且已经 运行 解决了一个简单的问题(我希望如此)。我可以使用 getInitialProps() 直接从我的 index.js 页面向浏览器呈现数据。我显然不想在我的索引页面上设置我的整个应用程序。
我遇到的问题是尝试将数据从子组件导入到索引页。使用与我的工作示例相同的代码,我得到了可怕的 "TypeError: Cannot read property 'map' of undefined" 错误。这个简单的 export/import 设置在 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 is not defined.
来自 Next.js 文档:
Note: getInitialProps can not be used in children components. Only in pages.