【发布时间】:2022-10-23 22:12:09
【问题描述】:
我试图根据上下文 API 中给出的属性调用货币,但每当我调用它时,都会得到错误:TypeError:无法读取 null 的属性(读取“useContext”)。但是当在我的主页中调用它而不将它传递给 getServerSideprops 时工作正常。请有人可以帮我解决这个问题
从“../context/cryptoContext”导入 {CryptoState} 从“反应”导入 { useContext };
const GetCurrency = async () => {
const {currency } = await useContext(CryptoState)
return currency
}
export default GetCurrency
import Head from 'next/head'
import GetCurrency from '../components/getCurrency';
export default function Home(jsonData) {
console.log(jsonData)
return (
<div className="bg-green-100 dark:bg-gray-800 pb-5 h-screen w-screen">
<Head>
<title>Crypto</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
</div>
)
}
export async function getServerSideProps(context) {
const currency = await GetCurrency();
const response = await fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=gecko_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h`)
return {
props: {
jsonData,
},
}
}
【问题讨论】:
-
这是否有助于回答您的问题:Nextjs and Context API?
标签: next.js react-context use-context