【问题标题】:React Hook is called in function "onSubmit" which is neither a React function component or a custom React Hook functionReact Hook 在函数“onSubmit”中调用,该函数既不是 React 函数组件也不是自定义 React Hook 函数
【发布时间】:2020-07-26 02:20:51
【问题描述】:

我有一个表单,我想在function onSubmit() 内的组件AddList() 中调用一个钩子function usePostAddList()。基本上usePostAddList() 是发出POST 请求。

这是AddList()的代码:

AddList.jsx

export default function AddList() {
..
..
const onSubmit = (e) => {
    e.preventDefault()

    const data = [
      {
        komoditas,
        areaKota,
        areaProvinsi,
        price,
        tglParsed,
      },
    ]

    // I called it here and it show an error
    usePostAddList(data)
}
..
..
}

reducer/index.js

export function usePostAddList(data) {
  const [state, dispatch] = React.useReducer(reducer, initState)

  React.useEffect(() => {
    dispatch({ type: ACTIONS.MAKE_REQUEST })
    store
      .append("Sheet2", data)
      .then((res) =>
        dispatch({
          type: ACTIONS.ADD_LIST,
          payload: res,
        })
      )
      .catch((e) => {
        return dispatch({
          type: ACTIONS.GET_ERRORS,
          payload: e,
        })
      })
  }, [])

  return state
}

我已经阅读了很多解决方案,例如我必须在函数名称中写“use”,将函数AddList大写,但仍然出现此错误:

React Hook "usePostAddList" is called in function "onSubmit" which is neither a React function component or a custom React Hook function

但如果我像下面的代码一样调用usePostAddList(),它会起作用:

AddList.jsx

export default function AddList() {
   const { lists, loading, errors } = usePostAddList("test")

   return (
      ...
   )
}

但这并没有解决我的问题

【问题讨论】:

  • 你的道具在哪里?
  • 你这是什么意思?
  • 错误是什么?钩子的规则之一是它们必须在组件的顶层调用,所以我怀疑这就是为什么 usePostAddList() 在你的第二个示例中不会出错,但是当它嵌套在 onSubmit 内时它会出错。
  • 那我该怎么办?我不能在函数内调用useReducer
  • 您是否在 AddList 文件中导入 React?

标签: javascript reactjs use-reducer


【解决方案1】:

您只能在功能组件内部和组件顶部使用挂钩。请查看rules of hooks 了解有关原因的更多信息。

您可以按如下方式使用自定义挂钩:

export default function AddList() {
 const [data,setData] = useState()
 const { lists, loading, errors } = usePostAddList(data)

 return (
  ...
 )
}

并在 onSubmit 函数中更新您的数据:

const onSubmit = (e) => {
 e.preventDefault()

 const data = [
  {
    komoditas,
    areaKota,
    areaProvinsi,
    price,
    tglParsed,
   },
 ]

 // Call set data
 setData(data)
}

【讨论】:

  • 这种方式会第一次调用 Post 请求。那不是没有必要吗?
  • 您可以在您的 post 请求中添加未定义的检查,以避免在数据未定义时发送请求。
猜你喜欢
  • 2022-08-07
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
  • 2021-11-27
  • 1970-01-01
  • 2023-02-19
  • 2020-08-26
  • 2019-10-21
相关资源
最近更新 更多