[英]The data fetched from an API doesn't populate the table in NextJS
我嘗試在 NextJS 中使用 API 調用填充表。 我使用getStaticProps
函數來獲取數據並將它們傳遞給組件。 我嘗試使用map()
函數來訪問對象中的每個數據,但它不起作用並且沒有填充所需的數據。 當我運行應用程序時,控制台輸出以下錯誤。
Warning: data for page "/" is 150 kB, this amount of data can reduce performance.
當我檢查頁面源時,它具有完整的 API 對象,但我不明白它為什么這樣做。 下面我放了index.js
和CountriesTable.js
的代碼
index.js
import Head from "next/head";
import CountriesTable from "../components/CountriesTable/CountriesTable";
import Layout from "../components/Layouts/layout";
import SearchInput from "../components/SearchInput/SearchInput";
import styles from "../styles/Home.module.css";
export default function HomePage({ countries }) {
return (
<Layout>
<div className={styles.counts}>found {countries.length} countries</div>
<SearchInput placeholder="Search for country" />
<CountriesTable countries={countries} />
</Layout>
);
}
export const getStaticProps = async () => {
const res = await fetch("https://restcountries.com/v3.1/region/asia");
const countries = await res.json();
return {
props: {
countries,
},
};
};
CountryTable.js
import styles from './CountriesTable.module.css';
export default function CountriesTable({countries}) {
return (
<div>
<div className={styles.heading}>
<button className={styles.heading_name}>
<div>Name</div>
</button>
<button className={styles.heading_population}>
<div>Population</div>
</button>
</div>
{countries.map((country) => {
<div className={styles.row}>
<div className={styles.name}>{country.name}</div>
<div className={styles.population}>{country.population}</div>
</div>
})}
</div>
);
};
如何解決控制台中的錯誤並用數據填充表? 蒂亞!
NextJS 是一個服務器渲染平台。 您傳遞給頁面/組件的任何道具都將在源代碼本身中serialized
。 因此,將trim data
為必要的字段非常重要。 否則,您將在 HTML 源代碼中看到整個 json。 (工作代碼和框)
將從 getStaticProps、getServerSideProps 或 getInitialProps 返回的數據量減少到僅用於呈現頁面的基本數據。
由於只需要name
和population
,我們可以僅使用這兩個屬性創建一個新數據集。 這也應該消除警告。
export const getStaticProps = async () => {
const res = await fetch("https://restcountries.com/v3.1/region/asia");
const countries = await res.json();
const countriesWithNamePopulation = countries.map((country) => ({
name: country.name.common,
population: country.population
}));
return {
props: {
countries: countriesWithNamePopulation
}
};
};
countries.map
需要返回聲明
{countries.map((country) => {
return (
<div>
<div>{country.name}</div>
<div>{country.population}</div>
</div>
);
})}
我無法重現您的控制台警告,但您缺少 map 函數中的 return 語句。
這對我有用:
{countries.map((country, index) => {
return(
<div key={index}>
<div>{country.name.common}</div>
<div>{country.population}</div>
</div>
)
})}
此外,您不能顯示 country.name 因為它是一個對象。 我使用的是有效的 country.name.common,因為它是一個字符串。 此外,您需要在 map 函數中向您的 div 添加一個鍵屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.