在 React 状态管理中,如何利用自定义 Hooks 提高组件的复用性?请提供示例。
在React应用中,自定义Hooks提供了一种强大的方法来复用状态逻辑,使得组件更加模块化和可维护。自定义Hooks本质上是React Hooks(如useState、useEffect)的组合,封装了复杂的业务逻辑,允许我们在不改变组件结构的情况下重用逻辑。下面通过一个具体的例子来说明如何使用自定义Hooks来提高组件的复用性。
示例场景
假设我们正在构建一个天气应用,该应用不仅需要从API获取当前天气信息,还支持用户保存喜欢的城市。为了满足这些需求,我们可以创建两个自定义Hooks:useWeather和useFavorites。
1. useWeather Hook
useWeather Hook负责从API获取当前天气信息。它接受城市名称作为参数,并返回天气数据和一个加载标志。
import { useState, useEffect } from 'react';
function useWeather(city) {
const [weather, setWeather] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchWeather() {
const response = await fetch(`https://api.example.com/weather?q=${city}`);
const data = await response.json();
setWeather(data);
setLoading(false);
}
fetchWeather();
}, [city]);
return { weather, loading };
}
2. useFavorites Hook
useFavorites Hook管理用户保存的喜欢城市列表。它提供了一个状态变量来存储收藏城市,并提供了添加和移除收藏城市的函数。
import { useState } from 'react';
function useFavorites() {
const [favorites, setFavorites] = useState(localStorage.getItem('favorites') ? JSON.parse(localStorage.getItem('favorites')) : []);
const addFavorite = (city) => {
setFavorites((prev) => [...prev, city]);
localStorage.setItem('favorites', JSON.stringify([...favorites, city]));
};
const removeFavorite = (city) => {
setFavorites((prev) => prev.filter((fav) => fav !== city));
localStorage.setItem('favorites', JSON.stringify(favorites.filter((fav) => fav !== city)));
};
return { favorites, addFavorite, removeFavorite };
}
在组件中使用自定义Hooks
现在,我们可以在组件中使用这些自定义Hooks,以充分利用React的状态管理和复用逻辑的能力。
import React from 'react';
import { useWeather } from './useWeather';
import { useFavorites } from './useFavorites';
function WeatherApp() {
const city = 'Beijing';
const { weather, loading } = useWeather(city);
const { favorites, addFavorite, removeFavorite } = useFavorites();
const handleFavorite = () => weather ? (favorites.includes(weather.name) ? removeFavorite(weather.name) : addFavorite(weather.name)) : null;
return (
<div>
<h1>Weather in {city}</h1>
{loading ? <p>Loading...</p> : <p>{weather.main.temp}°C</p>}
<button onClick={handleFavorite}>{favorites.includes(city) ? 'Unfavorite' : 'Favorite'}</button>
</div>
);
}
export default WeatherApp;
这样,通过创建和使用自定义Hooks,我们不仅提高了代码的可读性,还提高了组件的复用性和可维护性。