【发布时间】:2022-01-28 20:37:09
【问题描述】:
我目前正在寻求帮助,因为 typescript 给了我以下错误,我在尝试编写 useReducer 时无法理解它。
TS2769:没有与此调用匹配的重载。重载 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]',给出了以下错误。 '(state: AuthState, action: AuthAction) => Error | 类型的参数{钱包:字符串|无效的;配置文件:{ [键:字符串]:对象 []; } | 无效的;帐户:{[键:字符串]:对象[]; } |无效的;错误:{ [键: 字符串]:对象[]; } |无效的; }' 不可分配给类型参数 'ReducerWithoutAction'。重载 2 of 5, '(reducer: (state: AuthState,动作:AuthAction) => 错误 | {钱包:字符串|无效的; 配置文件:{ [键:字符串]:对象 []; } |无效的;帐户:{ [密钥: 字符串]:对象[]; } |无效的;错误: { ...; } |无效的; },初始状态: never, initializer?: undefined): [...]',给出了以下错误。 'AuthState' 类型的参数不能分配给'never' 类型的参数。
import React from 'react'
type AuthState = {
wallet: string | null,
profile: { [key: string]: Object[] } | null,
account: { [key: string]: Object[] } | null,
error: { [key: string]: Object[] } | null,
}
type AuthAction = {
type: 'SET_WALLET' | 'SET_ACCOUNT' | 'SET_ERROR' | 'LOGOUT',
payload: AuthState
}
const initialState: AuthState = {
wallet: null,
profile: null,
account: null,
error: null
}
const authReducer = (state: AuthState, action: AuthAction) => {
switch (action.type) {
case 'SET_WALLET':
return {...state, wallet: action.payload.wallet}
case 'SET_ACCOUNT':
return {...state, profile: action.payload.profile, account: action.payload.account}
case 'SET_ERROR':
return {...state, error: action.payload.error}
case 'LOGOUT':
return {...state, wallet: action.payload.wallet}
default:
return new Error(`Unhandled action type ${action.type}`)
}
}
const AuthContext = React.createContext(initialState)
type Props = {
children: JSX.Element
}
const AuthProvider = ({children}: Props) => {
const [state, dispatch] = React.useReducer(authReducer, initialState)
const value = {state, dispatch}
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
export {AuthContext, AuthProvider}
如果有人可以帮助我理解这是为什么以及我做错了什么。
【问题讨论】:
标签: reactjs typescript