React Redux调度函数:期望0个参数,但得到1个 TS2554

3

需要翻译的内容:

此代码如下所示:

// Actions (in a separate file)
export const contextFilesAddAction = (payload: IContextFile) => ({
  type: CONTEXT_FILES_ADD,
  payload,
})

...

const App = () => {
  const [contextFiles, dispatch] = React.useReducer(contextFilesReducer, [])
  const contextFilesAdd = (payload: IContextFile) =>
    dispatch(contextFilesAddAction(payload))
  const contextFilesRemove = (id: string) =>
    dispatch(contextFilesRemoveAction(id))
  const contextFilesClear = () => dispatch(contextFilesClearAction())
  const contextFilesGet = (id: string) => {
    const ctxFile = contextFiles.find(f => f.id === id)
    if (typeof ctxFile === 'undefined') {
      throw Error('No context file found')
    }
    return ctxFile
  }
...

在每个dispatch行上,我都会收到标题中所述的错误。

当我查看这些函数的定义时,我可以看到直接紧邻它们的是一个重载函数,该函数接受一个参数,就像在这里使用的一样。

有没有什么原因选择不接受参数的重载函数?


你能提供一些关于contextFilesAddAction这个动作的代码吗? - keikai
当然,我已经在帖子中添加了一些信息。 - Tyler
1个回答

0

你需要为 useReducer 添加类型。

当我使用来自 @reduxjs/toolkitcreateAction 时,我遇到了相同的错误。

这是我的代码:

export const setClientId = createAction('setClientId');

setClientId('abc') // would throw error, expected 0 
//arguments but got 1, realized that I also need to provide type of argument

//Solution : add <string> after createAction
export const setClientId = createAction<string>('setClientId');

setClientId('abc') // works well.




网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接