javascript - 我不能在 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 (
解决方案
推荐阅读
- android - Android Firebase java.lang.NoSuchMethodError:类中没有虚拟方法zzbqo()Z
- powerbi - PowerBI Embedded,书签窗格未显示
- c++ - Leetcode 297 序列化和反序列化二叉树
- c# - 控制台应用程序的一部分在 C# 几分钟后停止工作。请自行复制并粘贴此控制台应用程序代码
- reactjs - 反应调度返回承诺而不是普通对象
- python - Pandas - 二进制矩阵和字符串数据(如何堆叠字符串数据/换行?)
- javascript - 无法在某些项目上使用浏览器
- php - 使用 wget 或 curl 使用 POST 数据登录网站
- c# - 所有 NuGet 版本到 .NET Framework 到 AssemblyVersionAttribute 映射的主列表?
- javascript - 在 JavaScript 中将结构化数据添加到数组