react常见bug - 查询条件变化,但page未重置为1
问题1.多次触发请求,且存在潜在的竞态问题
const [page, setPage] = useState(1); const [keyword, setKeyword] = useState(''); useEffect(() => { // do request }, [page, keyword]); useEffect(() => { setPage(1); }, [keyword]);
问题2.查询条件变化,但page未重置为1
const [page, setPage] = useState(1); const [keyword, setKeyword] = useState(''); useEffect(() => { // do request }, [page, keyword]);
以上问题的改进方法:推荐使用第三方库:https://ahooks.js.org/zh-CN/hooks/use-pagination
import { usePagination } from 'ahooks'; const [keyword, setKeyword] = useState(''); const { data, loading, pagination } = usePagination( ({ current, pageSize }) => { return requestXXX(); { refreshDeps: [keyword], }, );