【问题标题】:React context state is not being updatedReact 上下文状态未更新
【发布时间】:2022-02-13 13:18:12
【问题描述】:

我有一个 next.js 应用程序,我正在尝试使用反应上下文来导出状态。但是,状态不会更新,并保持为由 createContext 挂钩设置的初始值,在这种情况下未定义。我是不是做错了什么?

这是我创建上下文的文件:

import { NextPage } from 'next';
import {
  useState,
  SyntheticEvent,
  createContext,
  useContext,
  ReactNode,
} from 'react';
import { TimeZoneType } from '../CompetitionList/types';

interface Props {
  children: ReactNode;
}

type ContextType = {
  timeZone: TimeZoneType;
  handleTimeZone: (_event: SyntheticEvent, _newZone: TimeZoneType) => void;
};

const TimeZone = createContext<ContextType>({} as ContextType);

const TimeZoneState: NextPage<Props> = ({ children }) => {
  const [timeZone, setTimeZone] = useState<TimeZoneType>('Local');
  const handleTimeZone = (_event: SyntheticEvent, newZone: TimeZoneType) => {
    if (newZone !== null) {
      setTimeZone(newZone);
    }
  };
  return (
    <TimeZone.Provider value={{ timeZone, handleTimeZone }}>
      {children}
    </TimeZone.Provider>
  );
};

export const useTimeZone = () => {
  return useContext(TimeZone);
};

我称上下文类似:

import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();
console.log({timeZone})
//returns undefined

对不起,如果这是一个不好的问题,这是我的第一个问题。

【问题讨论】:

  • 您将上下文提供程序放在哪里?确保您使用上下文的组件在您的提供程序中。
  • @SamiElk 我将上下文提供程序放在'../components/GlobalVariables/TimeZone' 的第一个代码块的末尾附近,并在提供程序中使用 {children}。这是我应该如何在不同的文件中获取状态值吗?

标签: reactjs typescript next.js use-state use-context


【解决方案1】:

我想我找到了解决方法。我只需要将我的 TimeZone.Provider 包装在我想使用上下文的组件周围。因此,我导出了 TimeZoneState 函数并将其包裹在 _app.tsx 中的页面组件中,如下所示:

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <TimeZoneState>
      <Component {...pageProps} />
    </TimeZoneState>
  );
};

export default MyApp

这让我可以在我的页面中以我想要的方式使用我的上下文。

import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 2021-09-18
    • 1970-01-01
    • 2015-06-11
    • 2021-03-02
    • 2021-07-20
    • 2019-08-08
    • 2019-05-30
    • 2021-07-30
    相关资源
    最近更新 更多