简体   繁体   English

React Typescript,类型''不可分配给类型'null'

[英]React Typescript, Type '' is not assignable to type 'null'

I have the start of s simple todo app in with React and typescript我使用 React 和 typescript 开始了一个简单的待办事项应用程序

I am creating a context but getting an error in the value of the content provider我正在创建一个上下文,但内容提供者的值出现错误

<TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider>

for the value I get the error对于我得到错误的值

Type '{ todoList: string[]; }' is not assignable to type 'null'.

What does error mean and how can i fix this typescript error错误是什么意思,我该如何解决这个 typescript 错误

import { createContext, useContext, useState, ReactChildren, ReactChild } from "react";

interface AuxProps {
    children: ReactChild | ReactChildren;
  }

const TodoContext = createContext(null)

const intialTodo = ['Learn Context']

const TodoProvider = ({children}:AuxProps) => {

    const [todoList, setTodoList] = useState<string[]>(intialTodo)

    const contextValue = {
        todoList
    }

    return(
        <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider>
    )
}

export const useTodoContext = () => useContext(TodoContext)

export default TodoProvider

Why are you assigning null to string array?为什么将 null 分配给字符串数组?

const TodoContext = createContext([])

does it work for your case?它适用于您的情况吗?

Because you are sending just null.因为您只发送 null。 but context needs null with type here like that但是上下文需要 null 类型在这里

const TodoContext = createContext(null as any)
render{
 const photosObject = this.context as any
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用TypeScript进行反应:类型“ {}”不可分配给类型 - React with TypeScript: Type '{}' is not assignable to type React TypeScript:类型“null”不可分配给类型“CanvasRenderingContext2D” - React TypeScript: Type 'null' is not assignable to type 'CanvasRenderingContext2D' React,typescript - 'string | 类型的参数 null' 不能分配给“字符串”类型的参数 - React, typescript - Argument of type 'string | null' is not assignable to parameter of type 'string' React Typescript不可分配给type参数 - React typescript is not assignable to parameter of type 类型不可分配(React + Typescript + Firebase) - Type not assignable (React + Typescript + Firebase) Typescript:“计时器”类型不可分配给“空”类型 - Typescript: Type 'Timer' is not assignable to type 'null' 打字稿:类型“ null”不可分配给类型错误 - Typescript: Type 'null' is not assignable to type error 类型“计时器”不可分配给 typescript 中的类型“空” - Type 'Timer' is not assignable to type 'null' in typescript React Typescript:类型参数不可分配给类型参数 - React Typescript: Argument of type is not assignable to parameter of type 与 TypeScript 反应:类型不可分配给类型“IntrinsicAttributes” - React with TypeScript: Type is not assignable to type 'IntrinsicAttributes'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM