【问题标题】:Using `useContext` with TypeScript - Type 'MyType | null` is not assignable to type 'MyType'将 `useContext` 与 TypeScript 一起使用 - 类型 'MyType | null` 不可分配给类型“MyType”
【发布时间】:2023-03-15 04:38:01
【问题描述】:

我正在努力在一个我一直在研究的小型代码库上实现 TypeScript,并且遇到了上述错误的一些问题。我已经搜索了答案,但似乎没有一个能解决我遇到的实际问题。

我收到了错误:

Type 'ContextType | null' is not assignable to type 'ContextType'.

我尝试将其设置为 null、undefined 和 object,但似乎没有任何帮助,所以我希望能得到一些帮助!

Store.txt

import { useReducer, createContext, useMemo } from "react";
import { INITIAL_DATA } from './todo/constants';
import { ContextType, ITodo, ACTIONTYPE } from './todo/models';
export const StoreContext = createContext<ContextType | null>(null)

export enum ACTIONS {
  DELETE_TODO = "delete_todo",
  ADD_TODO = "add_todo",
};

const reducer = (state: ITodo, action: ACTIONTYPE) => {
  switch (action.type) {
    case ACTIONS.DELETE_TODO:
      return [...action.payload];
    case ACTIONS.ADD_TODO:
      return action.payload;
    default:
      return state;
  }
};

interface Props {
  children: React.ReactNode;
}

export const StoreProvider = ({ children }: Props) => {
  const [state, dispatch] = useReducer(reducer, INITIAL_DATA);
  const contextValue: ContextType = useMemo(() => {
    return { state, dispatch };
  }, [state, dispatch]);

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

Component.tsx

import { useContext } from 'react';

import { StoreContext, ACTIONS } from '../../../store';
import { ContextType } from '../../models'


export const AddTodo = () => {
  const { state, dispatch }: ContextType = useContext(StoreContext);

  const validateFirstStep = async () => {
    return await isValid(firstStepForm);
  }

  const closeDrawer = () => {
    onClose();
  }

  const handleSubmit = async () => {
    const newTodoEntry = { /** todo **/ }
    const newData = [...state, newTodoEntry];

    dispatch({ type: ACTIONS.ADD_TODO, payload: newData });
  }

  return (
    <div>
     { /* Something Todo happens here */ }
    </div>
  )
}

Models.tsx

import { ACTIONS } from '../../store';

export type ITodos = {
  id: string;
  todoName: string;
  todoType: string;
}[];

export type ContextType = {
  state: ITodos;
  dispatch: React.Dispatch<ACTIONTYPE>;
}

export type ACTIONTYPE =
  | { type: ACTIONS.ADD_TODO, payload: ITodos }
  | { type: ACTIONS.DELETE_TODO; payload: ITodos }

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    如果反应树中没有更高的提供者,您需要提供默认上下文值;

    export const StoreContext = createContext<ContextType>({todos: [], dispatch: () => {}})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2017-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 1970-01-01
      相关资源
      最近更新 更多