[英]Next.js import fetch data from child component to parent page in React
我正在使用 Next.js 將我的 CRA 轉換為 SSR 應用程序。 我剛剛開始並且已經遇到了一個簡單的問題(我希望)。 我可以使用 getInitialProps() 直接從我的 index.js 頁面將數據呈現到瀏覽器。 我顯然不想在我的索引頁面上設置我的整個應用程序。
我遇到的問題是嘗試將數據從子組件導入索引頁面。 使用與我的工作示例相同的代碼,我得到了可怕的“TypeError:無法讀取未定義的屬性‘地圖’”錯誤。 這個簡單的導出/導入設置在 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 未定義。
來自 Next.js 文檔:
注意:getInitialProps 不能在子組件中使用。 僅在頁面中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.