gpt4 book ai didi

reactjs - useReducer 的 initialState 类型为 never?

转载 作者:搜寻专家 更新时间:2023-10-30 20:36:48 25 4
gpt4 key购买 nike

initialState 有错误:Argument of type '{ email: string;密码:字符串;有效: bool 值; }' 不可分配给 '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 的预期返回值有助于捕获此类问题。

最佳答案

我也遇到过这个问题。在我看来,防止错误的最佳方法是将状态接口(interface)添加为 reducer 的返回类型。然后你会在 useReducer 行看到 reducer 内部的类型错误。

像这样:

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

关于reactjs - useReducer 的 initialState 类型为 never?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54771003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com