OpenCV中的VideoCapture后端参数详解斜
2026/4/13 9:03:35
自定义 Hooks 是逻辑复用的重要方式,其设计需要考虑可重用性和边界情况。
// 自定义数据获取 HookfunctionuseApi(url,options={}){const[data,setData]=useState(null)const[loading,setLoading]=useState(true)const[error,setError]=useState(null)useEffect(()=>{letcancelled=falseconstfetchData=async()=>{try{setLoading(true)constresponse=awaitfetch(url,options)constresult=awaitresponse.json()// 避免组件卸载后的状态更新if(!cancelled){setData(result)setError(null)}}catch(err){if(!cancelled){setError(err)setData(null)}}finally{if(!cancelled){setLoading(false)}}}fetchData()// 清理函数return()=>{cancelled=true}},[url])return{data,loading,error}}// 使用示例functionUserProfile({userId}){const{data:user,loading,error}=useApi(`/api/users/${userId}`)if(loading)return<div>加载中...</div>if(error)return<div>错误:{error.message}</div>if(!user)return<div>用户不存在</div>return<div>用户名:{user.name}</div>}