如何在包含 useEffect 和 useReducer 的点击事件上使用自定义钩子?
我正在使用包含 useEffect 和 useReducer 的自定义钩子进行 API 调用,并且我在单击按钮时调用此自定义钩子,并且收到此错误(React Hook“useAuth”在函数“handleClick”中调用,该函数既不是 React 函数组件,也不是自定义函数)反应钩子函数)。 代码如下
useAuth.js
import axios from 'axios'
import {useEffect,useReducer} from 'react'
const ACTION = {
LOADING:'loading',
SUCCESS:'success',
ERROR:'error'
}
function reducer(state,action) {
switch (action) {
case ACTION.LOADING:
return {loading:true,data:[]}
case ACTION.SUCCESS:
return {...state,loading:false,data:action.payload.data}
case ACTION.ERROR:
return {...state,loading:false,data:[],error:action.payload.error}
default:
break;
}
}
function useAuth (data) {
const [state, dispatch] = useReducer(reducer, {data:[],loading:true})
useEffect(() => {
dispatch({type:ACTION.LOADING})
const getData = async ()=>{
try {
const response = await axios.post('https://expamle.com',data)
dispatch({type:ACTION.SUCCESS,payload:{data:response.data.data}})
} catch (error) {
dispatch({type:ACTION.ERROR,payload:{data:error.response}})
}
}
getData()
}, [])
return state
}
export default useAuth
app.js
import logo from './logo.svg';
import './App.css';
import useAuth from './useAuth'
function App() {
// const {loading,data,error} = useAuth()
const handleClick = () => {
const {loading,data,error} = useAuth() // how to use custom hook on click event
}
return (
<div className="App">
<button onClick={handleClick}></button>
</div>
);
}
export default App;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理想情况下,应该这样写
在您的 useAuth 挂钩中,您应该有一个在单击按钮时变为 true 的标志
Ideally, it should be written like this
In your useAuth hook you should have a flag that becomes true upon button click
用户ducer
似乎太多了。我建议一个简单的useasync
,您可以使用
useasync
进行任何异步行为。现在,您可以编写useAuth
,要在
app
中使用它,请参见
useasync
的完整演示, this Q&amp; a 。useReducer
seems too much for this. I would suggest a simpleuseAsync
,You can use
useAsync
for any asynchronous behavior. Now you can writeuseAuth
,To use it in your
App
,See a full demo of
useAsync
in this Q&A.