我有一个表单,我想在function usePostAddList()
内的组件AddList()
中调用钩子function onSubmit()
。基本上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 (
...
)
}
但这并不能解决我的问题
答案 0 :(得分:3)
您只能在功能组件内部以及组件顶部使用挂钩。检查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)
}