useReducer 的 initialState 被输入为 never?

IT技术 reactjs typescript
2021-04-26 12:00:40

initialState 有错误:类型为 '{ email: string; 的参数;密码:字符串;有效:布尔值;}' 不可分配给类型为 'never'.ts(2345) 的参数


function reducer(state: IState, action: IFluxAction) {
  const Users = UsersFetch()
  switch (action.type) {
    case 'email':
      const email = action.value
      const valid = Users.find(e => e === email) ? true : false

      return {
        email,
        valid,
      }
    case 'password':
      const password = action.value
      return {
        password,
      }
    default:
      throw new Error()
  }
}
  const initialState = {
    email: '',
    password: '',
    valid: false,
  }
  const [state, dispatch] = React.useReducer(reducer, initialState)

键入此内容以满足错误的正确方法是什么?

react 16.8.1 typescript 3.3.1

应该(通过) 添加...state到回报中,例如

  switch (action.type) {
    case 'email':
      const email = action.value
      const valid = Users.find(e => e === email) ? true : false

      return {
        ...state,
        email,
        valid,
      }
    case 'password':
      const password = action.value
      return {
        ...state,
        password,
      }
    default:
      throw new Error()
  }

此外 - 正如@madflanderz 所建议的,将 IState 设置为 reducer 的预期返回值有助于捕捉这样的问题。

2个回答

我也遇到了这个问题。在我看来,防止错误的最佳方法是将状态接口添加为减速器的返回类型。然后您会在 useReducer 行上看到 reducer 中的类型错误。

像这样:

function reducer(state: IState, action: IFluxAction): IState {
   // reducer code
   // type errors are visible here 
}

问题很可能与您的减速器声明有关。initialState的类型必须是相同的减速功能状态的类型和返回值。

这将起作用:

function reducer(state: {email: string}) {
  return state
}
const initialState = {
  email: '',
}
const [state, dispatch] = React.useReducer(reducer, initialState)

这会产生一个错误:

// state has a different type than initialState.
function reducer(state: {address: string}) {
  // No return statement.
}
const initialState = {
  email: '',
}
const [state, dispatch] = React.useReducer(reducer, initialState) // Error

在作出react的类型,你可以看到的是,useReducer通用的函数总是期望initialState类型是一个的ReducerState<R>类型。ReducerState<R>是一种有条件的类型,试图推断出正确的状态的类型和回退到never如果失败。