【问题标题】:How to make Context work in React using Typescript?如何使用 Typescript 让 Context 在 React 中工作?
【发布时间】:2023-01-18 08:57:23
【问题描述】:

我正在尝试在 Typescript 中为我的 Next.js 应用程序设置上下文提供程序。

我之前在纯 JS 的 React 中设置了一个上下文提供程序,所以这是我学习 TS 的机会。

在下面的代码中,Context.Providervalue={} 属性返回错误:

Property 'tasks' is missing in type '(State | Dispatch<SetStateAction<State>>)[]' but required in type 'State'

import { createContext, useState } from "react";
import { ReactNode } from "react";

interface Task {
    name: string,
    finished: boolean
}

interface State {
    tasks: Task[]
}

const initialState: State = {
    tasks: []
}

export const Context = createContext<State>(initialState)

type stateProps = {
    children: ReactNode
}
const StateContext = ({ children }: stateProps) => {
    const [state, setState] = useState<State>(initialState)

    return (
        <Context.Provider value={[state, setState]}>
            {children}
        </Context.Provider>
    )
}

export default StateContext;

出于某种原因,它说 tasks 在类型为 (State | Dispatch&lt;SetStateAction&lt;State&gt;&gt;)[] 的东西中丢失,我不知道在哪里。

我在学习 TS 时遇到了很多其他问题,但出于某种原因我无法解决这个问题。有任何想法吗?

【问题讨论】:

  • 你已经说过你的上下文值是State类型,它是一个键为tasks的对象,但是你将上下文的值设置为[state, setState]的数组,它没有tasks关键在上面。确保您的编辑器设置正确,以显示与您的代码内联的打字稿错误。

标签: javascript reactjs typescript typescript-generics react-typescript


【解决方案1】:

value 必须与 createContext 中指定的类型具有相同的形状,在本例中为 State

你的useState已经持有一个State,直接传给value就可以了

const [state, setState] = useState<State>(initialState)

return (
    <Context.Provider value={state}>

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2018-12-31
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2021-09-26
    相关资源
    最近更新 更多