【问题标题】:how can i use context API and getserversideprops in nextjs我如何在 nextjs 中使用上下文 API 和 getserversideprops
【发布时间】: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,
    },
  }
}

【问题讨论】:

标签: next.js react-context use-context


【解决方案1】:

它是关于客户端和服务器端代码的。 getServerSideProps 在服务器端执行,上下文用于客户端。您不会在服务器端获得客户端上下文。您可以使用swr用于客户端数据获取。上下文将与swr 一起顺利工作。

否则,您可以将货币存储在 cookie 中,并且可以从服务器端的 cookie 中获取值。

【讨论】:

    【解决方案2】:

    看来我错了,conext也可以在服务器端工作

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2019-06-05
      • 2021-12-31
      • 2021-05-15
      • 2021-03-03
      • 2021-01-13
      • 2021-12-02
      • 2021-09-01
      • 2021-04-22
      相关资源
      最近更新 更多