类型 '{ userInfo: string | null; }' 的参数不可分配给类型 'never' 的参数



我正在尝试创建上下文api,以使用typescript在react中存储用户详细信息和令牌。由于我是typescript的新手,我无法理解以下错误,请提供帮助。

代码:

import { createContext, useReducer } from "react";
type Action =
| { type: "USER_LOGIN_REQUEST"; }
| { type: "USER_LOGIN_SUCCESS";payload: string}
| { type: "USER_LOGIN_FAIL"; payload: string };
interface UserAuthProviderProps {
children: React.ReactNode;
}
type AppState = typeof INITIAL_STATE;
const INITIAL_STATE = {
userInfo: localStorage.getItem("userInfo")
? localStorage.getItem("userInfo")
: null,
};
const userLoginreducer = (state: AppState, action: Action) => {
switch (action.type) {
case "USER_LOGIN_REQUEST":
return { loading: true };
case "USER_LOGIN_SUCCESS":
return { loading: false, success: true, userInfo: action.payload };
case "USER_LOGIN_FAIL":
return { loading: false, error: action.payload };
default:
return state
}
};
const UserAuthContext = createContext<{
state: AppState;
dispatch: React.Dispatch<Action>;
}>(INITIAL_STATE);
function UserAuthProvider({ children }: UserAuthProviderProps) {
const [state, dispatch] = useReducer(userLoginreducer, INITIAL_STATE);
return (
<UserAuthContext.Provider value={{ state, dispatch }}>
{children}
</UserAuthContext.Provider>
);
}
export { UserAuthContext, UserAuthProvider };

错误

Type '{ userInfo: string | null; }' is missing the following properties from type '{ state: 
{ userInfo: string | null; }; dispatch: Dispatch<Action>; }': state, dispatch
Argument of type '{ userInfo: string | null; }' is not assignable to parameter of type 
'never'.

您的上下文应该具有类型AppState:

type AppState = {
userInfo: string | null,
success: boolean,
error: string,
};
const INITIAL_STATE: AppState = {
userInfo: localStorage.getItem('userInfo')
? localStorage.getItem('userInfo')
: null,
success: true,
error: '',
};
const UserAuthContext = createContext<AppState>(INITIAL_STATE);

相关内容

最新更新