【问题标题】:React Context not updating value to pass to another pageReact Context 不更新值以传递到另一个页面
【发布时间】:2021-08-13 12:57:13
【问题描述】:

我正在使用Nextjs 创建一个电子商务应用程序,并希望在页面之间共享数据。我知道我们不能使用props 在页面之间传递数据,因此正在研究反应context api。这是我第一次使用 react context 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

但是,此 productData 无法从其他页面访问,并且反应上下文状态未更新。 知道为什么会发生这种情况吗?

【问题讨论】:

  • 您是否在_app.js 文件中使用了提供程序?
  • 是的,我做到了。我将 _app.js 添加到上述问题中。
  • @SifatHaque 我注意到状态在 slug 页面上更新,但是当我移动到另一个页面时,状态会重置。
  • 请确保您的页面在页面之间移动时没有刷新。
  • 在页面之间移动需要使用 next.js 链接。你可以从这里检查。 nextjs.org/docs/api-reference/next/link

标签: reactjs next.js react-context


【解决方案1】:

一旦您更新了上下文值。请确保您使用next/link 在页面之间导航。这是next/link的详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多