首页 > 解决方案 > 我不能在 TypeScript 中使用 useContext Hook

问题描述

我正在尝试使用 TypeScript 和 Context API 制作待办事项应用程序,但我无法将待办事项的上下文与 useContext Hook 一起使用。

创建上下文,这里我创建了数组待办事项的接口并创建了它的上下文。

const todos = [
    { todo: 'Make Break Fast', id: 1, completed: true },
    { todo: 'React Book', id: 2, completed: false },
    { todo: 'Start Coding', id: 3, completed: false },
]


interface ITodos {
    todo: string
    id: number
    completed: boolean
}

export const TodoContext = createContext<ITodos[]>(todos);

Global Provider,在这里我创建了 Context Provider 并将其子 (JSX.Elements) 作为 Props 传递。

interface IChildrenProp {
    children: React.ReactNode
}

const ContextProvider = ({ children }: IChildrenProp): JSX.Element => {

    return <TodoContext.Provider value={todos}>
        {children}
    </TodoContext.Provider>
}

export default ContextProvider;

使用 Context,在这里我期待使用 TodoContext 中的 useCotext Hook 的待办事项列表。

import React, { useContext } from 'react'
import TodoContext from './store/context'




const Todo: React.FC = (): JSX.Element => {

    const todos = useContext(TodoContext)

    return (
        <>
            <h1>My Todo List</h1>
            <input id='todo' placeholder='e.g. Read Book' />

        </>
    )
}

export default Todo

错误,但出现以下错误。

TypeScript error in /typescript/todo-app/src/Todo.tsx(9,30):
Argument of type '({ children }: IChildrenProp) => JSX.Element' is not assignable to parameter of type 'Context<unknown>'.
  Type '({ children }: IChildrenProp) => Element' is missing the following properties from type 'Context<unknown>': Provider, Consumer  TS2345

     7 | const Todo: React.FC = (): JSX.Element => {
     8 | 
  >  9 |     const todos = useContext(TodoContext)
       |                              ^
    10 | 
    11 | 
    12 |     return (

标签: javascriptreactjstypescriptreact-context

解决方案


推荐阅读