【问题标题】:How to pass a type down to a React Context Consumer in Typescript如何在 Typescript 中将类型传递给 React 上下文使用者
【发布时间】:2020-07-11 04:34:02
【问题描述】:

我想创建一个 React Context 并将 statesetState 属性 useState 挂钩到消费者。

我有一个Step 和一个Context 类型:

type Step = {
  step: string;
};

type Context = {
  step: Step;
  setStep: Dispatch<SetStateAction<Step>>;
};

我创建了一个上下文:

export const StepContext = createContext<Context | undefined>(undefined);

我创建了一个StepProvider 和一个钩子:

const StepProvider = ({ children }: { children: ReactNode }) => {
  const [step, setStep] = useState<Step>({ step: 'one' });
  return <StepContext.Provider value={{ step, setStep }}>{children}</StepContext.Provider>;
};

我创建了一个StepConsumer

const StepConsumer = () => {
  const { step, setStep } = useContext(StepContext);
  return <div>{...}</div>;
};

但在:

const { step } = useContext(StepContext)

stepsetStep 返回以下错误TS2339: Property 'step' does not exist on type 'Context | undefined'

我没有以正确的方式传递类型吗?

谢谢

【问题讨论】:

标签: reactjs typescript typescript-typings


【解决方案1】:

您的语法是正确的,但上下文的使用不够彻底,无法确保解构时值不是undefined

错误本身由 strictNullChecks 编译器选项检查,如果在您的 tsconfig 中设置了 strictNullChecks: false,您的代码将在当前状态下运行。

但是,要保持该选项处于启用状态,您需要在解构或使用 StepContext 值之前确保上下文值不是 undefined,Typescript 不会让您在没有先检查的情况下访问它。

如果您将解构更改为简单赋值,然后检查上下文不是undefined,则错误将消失。

const stepContext = React.useContext(StepContext);

if (typeof stepContext !== "undefined") {
  stepContext.setStep("foo")
}

// simplified
if (stepContext) {
  stepContext.setStep("foo")
}

// simplified further
stepContext?.setStep("foo");

此外,您还可以使用strictNullChecks: false 定义没有undefined 类型值的上下文类型。

export const StepContext = createContext<Context>(undefined);

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 2018-03-05
    • 1970-01-01
    • 2021-04-23
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多