如何通过 Context 和 typescript 管理状态
How to manage state through Context and typescript
所以我正在尝试学习如何使用上下文,因为我正在为狗构建一个约会应用程序,就像一个有趣的项目,并且必须在整个应用程序中传递当前用户。
不过我似乎不明白如何将上下文与打字稿一起使用。我有一个名为 HomeView 的组件,我想查看计数器并可能使用 usestate 函数 setCounter 设置计数器。
当我尝试在我的 HomeView 组件中记录计数器时,我得到的所有内容都是未定义的,即使该值设置为 0。我应该能够在我的消费者屏幕上记录 0。我错过了什么?
Contex.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>
);
};
由于您正在检索未嵌套在 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>
);
};
所以我正在尝试学习如何使用上下文,因为我正在为狗构建一个约会应用程序,就像一个有趣的项目,并且必须在整个应用程序中传递当前用户。
不过我似乎不明白如何将上下文与打字稿一起使用。我有一个名为 HomeView 的组件,我想查看计数器并可能使用 usestate 函数 setCounter 设置计数器。
当我尝试在我的 HomeView 组件中记录计数器时,我得到的所有内容都是未定义的,即使该值设置为 0。我应该能够在我的消费者屏幕上记录 0。我错过了什么?
Contex.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>
);
};
由于您正在检索未嵌套在 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>
);
};