[英]React Hook "useState" is called in function "setResults" which is neither a React function component or a custom React Hook function
[英]React Hook is called in function “onSubmit” which is neither a React function component or a custom React Hook function
我有一個表格,我想在function onSubmit()
AddList()
) 中調用鈎子function usePostAddList()
) 。 基本上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
}
我已經閱讀了許多解決方案,例如我必須為 function 的名稱寫“使用”,大寫 function 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 (
...
)
}
但這並沒有解決我的問題
您只能在功能組件內部和組件頂部使用掛鈎。 檢查鈎子規則以獲取有關原因的更多信息。
您可以按如下方式使用自定義掛鈎:
export default function AddList() {
const [data,setData] = useState()
const { lists, loading, errors } = usePostAddList(data)
return (
...
)
}
並在 onSubmit function 更新您的數據:
const onSubmit = (e) => {
e.preventDefault()
const data = [
{
komoditas,
areaKota,
areaProvinsi,
price,
tglParsed,
},
]
// Call set data
setData(data)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.