2

我有一个表单,我想function usePostAddList()AddList(). function onSubmit()基本上usePostAddList()就是提出POST请求。

这是代码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)
}
..
..
}

减速器/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()下面以某种方式调用了类似的代码,它就起作用了:

添加列表.jsx

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

   return (
      ...
   )
}

但这并没有解决我的问题

4

1 回答 1

5

您只能在功能组件内部和组件顶部使用挂钩。检查钩子规则以获取有关原因的更多信息。

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

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)
}
于 2020-07-26T06:27:46.990 回答