【问题标题】:How to manage state through Context and typescript如何通过 Context 和 typescript 管理状态
【发布时间】:2022-01-04 13:49:48
【问题描述】:

所以我正在尝试学习如何使用上下文,因为我正在为狗构建一个约会应用程序只是作为一个有趣的项目,并且必须在整个应用程序中传递当前用户。

虽然我似乎没有掌握如何在打字稿中使用上下文。我有一个名为 HomeView 的组件,想查看计数器并可能使用 usestate 函数 setCounter 设置计数器。

当我尝试在我的 HomeView 组件中记录计数器时,即使值设置为 0,我得到的结果都是未定义的。我应该能够在我的消费者的屏幕上记录 0。我错过了什么?

Context.tsx

import { createContext, useState } from 'react';

type ContextType = {
  setCounter: React.Dispatch<React.SetStateAction<number>>;
  counter: number;
};

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

export const CounterContextProvider: React.FC = ({ children }) => {
  const [counter, setCounter] = useState(0);

  return <CounterContext.Provider value={{ counter, setCounter }}>{children}</CounterContext.Provider>;
};

HomeView.tsx

export const HomeView = () => {
  const context = useContext(CounterContext);
  console.log(context.counter); // value is undefined

  return (
    <div className='signInWrapper'>
      <SignIn />
      <CounterContextProvider>
        {context.counter}  // Nothing is shown onto the screen
      </CounterContextProvider>
    </div>
  );
};

【问题讨论】:

  • HomeView 需要是 CounterContextProvider 的子级。此外,这与 Typescript 无关,Typescript 只是 JavaScript 的一个糟糕版本。

标签: javascript reactjs typescript types react-context


【解决方案1】:

由于您在未嵌套在 CounterContext.Provider 本身的组件中检索上下文,因此您将获得 undefined

您应该将整个应用程序嵌套在 CounterContextProvider 中,以便全局访问状态。
您可以在 App.js 文件中执行此操作:

function App() {
  return (
    <CounterContextProvider>
        ...
        <HomeView/>
    </CounterContextProvider>

在此之后,您应该能够访问 HomeView 组件中的上下文:

export const HomeView = () => {
  const { counter, setCounter } = useContext(CounterContext);

  return (
    <div className='signInWrapper'>
      <SignIn />
      Your counter value is: {counter}
    </div>
  );
};

【讨论】:

  • 谢谢!! ? 这有效
猜你喜欢
  • 2020-08-14
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多