React Hook for a POST call onClick



我有一个按钮,该按钮的onClick我想用一些数据进行POST调用,用户已经填写了一个输入字段,存储在状态中,然后将用户重定向到另一个页面。

我当前的代码看起来是这样的,但我得到了一个错误:

React Hook"usePost"在函数"中被调用;onAccept";既不是React功能组件,也不是自定义React Hook功能

并且代码不起作用。我已经为POST调用创建了自己的挂钩。

有什么方法可以使所需的功能发挥作用?

我所追求的是能够进行POST调用和重定向。

简化示例:

// my function
const onAccept = () => {
const { data, loading, error } = usePost(
"MY_URL",
{ DATA: MY_DATA }
);
if (data && !error) {
navigate(`/`);
}
};
// return
<button onClick={() => onAccept()}
是的,您正在onAccept函数内部调用usePost钩子。你们应该遵循反钩规则。

为了解决你的问题,你可以这样做:

您的自定义挂钩文件:

export const usePost = () => {
const [status, setStatus] = useState()
const handlePost = useCallback(async (url, data) => {
// your api request logic in here, bellow only show example
try {
const {data, status} = await apiCall(url, data)
if (data && status === 200) navigate(`/`)
} catch (error) {
console.log(error)
}
}, [])
return { handlePost }
// to return status to component, you can use bellow.
// return { status, handlePost }
}

然后你的组件:

const YourComponent: React.FC = () => {
const { handlePost } = usePost()
// To get status: const { status, handlePost } = usePost()
// your other hooks in here
// Check status
useEffect(() => {
if (status === 200) {
// whatever you want to do
}
}, [status])

return (
<>
// Your component UI here
...
<button onClick={() => handlePost(url, data)}>
</>
)
}

您应该在组件的顶层调用自定义挂钩(例如:usePost(,而不是像在代码中那样嵌套函数体(onAccept函数体(。

我可以建议您执行以下操作。

首先,您应该创建将从usePost hook返回的fetch函数。

例如。

export const usePost = () => {
const [loading, setLoading] = useState(false)
const [data, setData] = useState([])
const fetch = () => {
setStatus(loading)
apiRequest({
url: 'my_url',
method: 'GET',

}).then(response => {
setStatus(false)
setData(response.data.data)
}).catch(e => {
setStatus(false)
})
}
return {
status,
data,
fetch
}

毕竟,您可以在组件中调用这个钩子。它将返回fetch函数。您应该在onAccept内部调用fetch。

示例。

const { data, loading, fetch } = usePost()
const onAccept = () => {
fetch()
}
// return
<button onClick={() => onAccept()}

PS。如果需要,也可以从usePost hook返回错误。

首先,从React Function调用钩子。阅读文档:https://reactjs.org/docs/hooks-rules.html#only-从react函数调用钩子。

其次,在usePost钩子中应该有某种load方法,例如:const { load } = usePost(...),以便在单击时发出POST请求。

所以你的处理程序看起来像:

const onAccept = () => {
load();
// the following block move somewhere before you render the component or better use useEffect hook for that
// if (data && !error) {
//   navigate(`/`);
// }
};

我希望这会有所帮助。

最新更新