React Context 不更新值以传递给另一个页面

React Context not updating value to pass to another page

我正在使用 Nextjs 创建一个电子商务应用程序并希望在页面之间共享数据。我知道我们不能使用 props 在页面之间传递数据,所以正在研究 React context api。这是我第一次使用 React 上下文 api。我研究过,发现你应该在 nextjs 的 _app.js 页面中添加 Provider。 但这在所有页面之间共享数据。另外,我的数据正在被应用程序的 slug 页面中的 getStaticProps 检索。我想将此数据放入我的应用程序的结帐页面。

这是我创建的上下文:

import { createContext, useState, useContext } from 'react';

const productContext = createContext({} as any);

export const ProductProvider = ({ children }) => {
  const [productData, setProductData] = useState('');
  return <productontext.Provider value={{ productData, setProductData }}>{children}</productContext.Provider>;
};

export const useProduct = () => useContext(productContext);

_app.js

import { ReportProvider } from '../contexts/ReportContext';
export default function CustomApp({ Component, pageProps }) {
  return (
  
            <ReportProvider>
              <Component {...pageProps} />
            </ReportProvider>
          
  );
}

我将其导入 slug 页面并尝试从此处更新状态

// [slug].js

import client from '../../client'
import {useProduct} from './productContext';

const Post = (props) => {
  const {setProductData} = useProduct();
  const { title = 'Missing title', name = 'Missing name' , price} = props
  setProductData(title);
  return (
    <article>
      <h1>{title}</h1>
      <span>By {name}</span>
      <button>
           <a href="/checkout">Buy Now</a>
     </button>
    </article>
  )
}

Post.getInitialProps = async function(context) {
  const { slug = "" } = context.query
  return await client.fetch(`
    *[_type == "post" && slug.current == $slug][0]{title, "name": author->name, price}
  `, { slug })
}

export default Post

但是无法从其他页面访问此产品数据,并且反应上下文状态未更新。 知道为什么会这样吗?

更新上下文值后。请确保您使用 next/link 在页面之间导航。这是关于 next/link

的详细信息