列表页是常用的功能,从后端获取列表数据,刷新到页面上。开发列表页需要考虑以下技术要点:1.如何翻页;2.如何进行内容搜索;3.何时进行页面刷新。
根据用户id获取用户列表,返回的state包括列表响应,加载状态,请求错误等信息。
const useFetchUserList = () => {
// useRequest Hook
const {state, doRequest} = useRequest();
// useAuth hook
const {user} = useAuth();
// 发起请求
const fetch = (userId, page, pageSize) => doRequest('http://vicyor.com/user/'+userId, {page:page,pageSize:pageSize},
{authorization:user.token}, 'POST' );
// 返回结果
return {state, fetch}
}
export const ListPage = () =>{
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const {state, fetch} = useFetchUserList();
const handleSearch = keyword => fetch(keyword, page, pageSize);
useEffect( () => {
fetch('', 1, pageSize);
},[])
return (<>
User List
setSearch( e.target.value )}
onSearch={handleSearch}
/>
>);
}
省份和城市服务,选择省份后选择对应的城市
const useProvinceAndCity = () => {
const {fetchProvince, provincesState} = useRequest('http://vicyor.com/province/list',{},{},'GET');
const {fetchCitys, citysState} = useRequest('http://vicyor.com/' + province + '/cityes', {}, {}, 'POST');
return {fetchProvince, fetchCitys, provincesState, citysState};
}
const CitySelector = () => {
const [selectedProvince, setSelectedProvince] = useState('');
const [selectedCity, setSelectedCity] = useState('');
const [fetchProvince, fetchCitys, provincesState, citysState] = useProvinceAndCitys();
// 初始加载所有省份
useEffect(() => {
fetchProvince();
},[])
const handleProvinceChange = (e) => {
setSelectedProvince(e.target.value);
// 加载所有城市
fetchCitys(selectedProvince);
};
const handleCityChange = (e) => {
setSelectedCity(e.target.value);
};
return (
);
};