我正在努力在我一直在研究的小型代碼庫上實作 TypeScript,但遇到了上述錯誤的一些麻煩。我一直在尋找答案,但似乎沒有一個能解決我遇到的實際問題。
我收到錯誤:
Type 'ContextType | null' is not assignable to type 'ContextType'.
我已經嘗試將它設定為 null、undefined 和 object,但似乎沒有任何幫助,所以我很感激這個幫助!
商店.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>
);
};
組件.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>
)
}
模型.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 }
uj5u.com熱心網友回復:
如果反應樹中沒有更高的提供者,您需要提供默認背景關系值;
export const StoreContext = createContext<ContextType>({todos: [], dispatch: () => {}})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368257.html
上一篇:理解TypeScript<Textendsany[]>
下一篇:錯誤TS2322:屬性'css'不存在于型別'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>,HTML
