Home Article Practice 自定义hooks

自定义hooks

2024-07-05 21:44  views:217  source:许某    

我们可以看到上面的组件,添加了一系列hooks和逻辑之后,已经变得非常的庞大。
那这时候我们怎么处理呢?hooks的一个非常的优势,就是能够很方便的提取自定义的hooks。
这个时候,我们就能把上面的一大堆逻辑抽取到一个单独的hooks中,方便复用和解耦。
function useHackerNewsApi = () => {
const [data, setData] = useState({ hits: [] });
const [url, setUrl] = useState(
'urladdress?query=redux',
);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(url);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
}, [url]);
const doFetch = () => {
setUrl(`urladdress?query=${query}`);
};
return { data, isLoading, isError, doFetch };
}
复制代码
在自定义的hooks抽离完成后,引入到组件中。
function App() {
const [query, setQuery] = useState('redux');
const { data, isLoading, isError, doFetch } =
useHackerNewsApi();
return (
<Fragment>
...
</Fragment>
);
}
然后我们需要在form组件中设定初始的后端URL
const useHackerNewsApi = () => {
...
useEffect(
...
);
const doFetch = url => {
setUrl(url);
};
return { data, isLoading, isError, doFetch };
};
function App() {
const [query, setQuery] = useState('redux');
const { data, isLoading, isError, doFetch } =
useHackerNewsApi();
return (
<Fragment>
<form
onSubmit={event => {
doFetch(
`urladdress?query=${query}`,
);
event.preventDefault();
}}
>
<input
type="text"
value={query}
onChange={event =>
setQuery(event.target.value)}
/>
<button type="submit">Search</button>
</form>
...
</Fragment>
);
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)