使用 useReducer 和 useEffect 的打字稿错误

时间:2020-12-28 21:05:37

标签: typescript redux react-hooks typescript-typings react-typescript

我已经创建了我的 reducer 函数,我已经将它导入到我的 #https://huggingface.co/Helsinki-NLP for other pretrained models from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-nl-en") model = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-nl-en") input_1 = df['Dutch_text'] input_ids = tokenizer("translate English to Dutch: "+input_1, return_tensors="pt").input_ids # Batch size 1 outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) 组件中并在 useReducer 中使用它,但是当它说没有重载匹配这个时,我不确定错误意味着什么打电话。这是错误的图像:

enter image description here

这是我的 eval "$(ssh-agent -s)" ssh-add ~/.ssh/<required-key>.pub 组件的代码:

MessengerDetailView

这就是我的 useShowSpell 函数目前的样子:

useShowSpell

我还在 import { useReducer, useEffect } from 'react'; import { apiGet } from '../utils'; import { reducer } from './reducers'; export const useShowSpell = (spellId: string) => { const [state, dispatch] = useReducer(reducer, { spell: null, isLoading: true, error: null, }); useEffect(() => { let isMounted = true; apiGet(`spells/${spellId}`) .then((results) => { if (isMounted) { dispatch({ type: 'FETCH_SUCCESS', spell: results }); } }) .catch((err) => { if (isMounted) { dispatch({ type: 'FETCH_FAIL', error: err.message }); } }); return () => { isMounted = false; }; }, [spellId]); return state; }; 组件中的 reducer 中遇到了一个次要错误,它说 预期 0 个参数,但得到 1 并且不太确定为什么我会当我使用 type SpellState = { spell?: any; isLoading: boolean; error?: string; }; type SpellAction = | { type: 'FETCH_SUCCESS'; spell: any } | { type: 'FETCH_FAILED'; error: string }; export const reducer = (prevState: SpellState, action: SpellAction) => { switch (action.type) { case 'FETCH_SUCCESS': { return { isLoading: false, error: null, spell: action.spell }; } case 'FETCH_FAILED': { return { ...prevState, isLoading: false, error: action.error }; } default: return prevState; } }; 时也会出现此错误。

关于为什么会发生这种情况的任何想法?谢谢!

1 个答案:

答案 0 :(得分:0)

  1. error 属性是可选的,这意味着它应该是 undefinedstring 类型。但是您将 null 分配给 reducer 中的 error 属性。

变化:

case 'FETCH_SUCCESS': {
  return { isLoading: false, error: null, spell: action.spell };
}

致:

case 'FETCH_SUCCESS': {
  return { isLoading: false, spell: action.spell };
}

传递给 error 的初始状态中的 useReducer 属性应该是 undefined,而不是 null

const [state, dispatch] = useReducer(reducer, {
  spell: null,
  isLoading: true,
  error: undefined,
});
  1. 操作类型为 FETCH_FAILED,而非 FETCH_FAIL。所以你应该把它修改为:
dispatch({ type: 'FETCH_FAILED', error: err.message });

源代码:https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/65484084