[英]I am trying to use a weather api that I am trying to pull data from i am getting undefined but the property does exist
[英]NextJS: I am getting undefined from api json data
我在控制台日志而不是數據中未定義
我的 Index.js(頁面文件)
import Head from "next/head";
import Link from "next/link";
import axios from "axios";
import Test from "../components/Test";
import styles from "../styles/Home.module.css";
function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Test />
</div>
);
}
export default Home;
我的 Test.js(組件文件)從中我得到錯誤
import React from "react";
import axios from "axios";
function Test({ data }) {
console.log(data);
return <div>Check console log log</div>;
}
export async function getStaticProps() {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com/todos/1`
);
return {
props: {
data,
},
};
}
export default Test;
控制台輸出
undefined
請幫幫我,我不知道為什么 axios,fetch 不起作用,但在pages/index.js 中工作
解決了! 數據從 pages/index.js 傳遞到 components/Test.js
我發現“getStaticProps”僅在頁面中的組件中不支持不知道為什么不支持
根據 Next.js 文檔, getStaticProps
方法適用於頁面組件,但不適用於子組件。 您調用了作為子組件的Test
。
您可以在頁面組件中獲取數據而不是通過 props 傳遞數據,然后您可以從子組件訪問數據如果您嘗試使用getStaticProps
。
例子:
索引.js
import Head from "next/head";
import Link from "next/link";
import axios from "axios";
import Test from "../components/Test";
import styles from "../styles/Home.module.css";
function Home({ data }) {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Test data={data} />
</div>
);
}
export async function getStaticProps() {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com/todos/1`
);
return {
props: {
data,
},
};
}
export default Home;
測試組件:
import React from "react";
function Test({ data }) {
console.log(data);
return <div>Check console log log</div>;
}
export default Test;
沒有直接在子組件中的 getStaticProps 和數據:
Index.js:(頁面)
import Head from "next/head";
import Link from "next/link";
import Test from "../components/Test";
import styles from "../styles/Home.module.css";
function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Test />
</div>
);
}
export default Home;
Test.js(組件):
import React from "react";
import useSWR from "swr";
import fetch from "isomorphic-unfetch";
const fetcher = (url) => fetch(url).then((r) => r.json());
function Test() {
const { data } = useSWR('yourURL', fetcher);
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
export default Test;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.