reactjs 当我刷新页面我的网址回到初始值MERN堆栈

z31licg0  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(163)

我使用了MERN堆栈,我想在前端创建如下代码:http://localhost:3000/products?color=0000&sort=latest&category=man等。我使用的是redux工具包,我的getProductSlice如下所示:

export const getProducts = createAsyncThunk(
      'product/get',
      async ({ page, sort, localValue, colorFilter, categoryFilter }, thunkAPI) => {
        let colorStr = colorFilter.substring(1);
        let url = `/api/v1/products?page=${page}&sort=${sort}&color=${colorStr}&cat=${categoryFilter}`;
        if (localValue) {
          url = url + `&search=${localValue}`;
        }
    
        try {
          const { data } = await axios.get(url);
          return data;
        } catch (error) {
          const message = error.response.data.msg;
          return thunkAPI.rejectWithValue(message);
        }
      }
    );

我的产品页面如下所示:

const dispatch = useDispatch();

  const {
    products,
    isLoading: loadingProducts,
    search,
    sort,
    numOfPages,
    page,
    sortOptions,
    uniqueColors,
    colorFilter,
    categoryFilter,
  } = useSelector(state => state.product);

  console.log(colorFilter, categoryFilter);

  useEffect(() => {
    dispatch(getCategories());
  }, [dispatch]);

  const { categories } = useSelector(state => state.category);

  const [localSearch, setLocalSearch] = useState('');
  const [localValue] = useDebounce(localSearch, 1000);

  const [value, setValue] = useState(sort);

  useEffect(() => {
    const queryParams = {
      page: page,
      sort: sort,
      localValue: localValue,
      colorFilter: colorFilter,
      categoryFilter: categoryFilter,
    };

    const searchParams = new URLSearchParams(queryParams);
    const queryString = searchParams.toString();

    window.history.replaceState(null, null, `/products?${queryString}`);

    dispatch(getProducts(queryParams));
  }, [dispatch, page, search, sort, localValue, colorFilter, categoryFilter]);

一切都很好,我的网址变化时,我搜索,页面,选择颜色等,但当我去页面=2当我刷新页面我的网址回到初始页面=1,和每一个过滤器

uqcuzwp8

uqcuzwp81#

应首先从searchParams获取页面、排序、搜索...的默认值
下面是我常用的代码:

import React, { useState } from "react";
import qs from "query-string";
import { useLocation, useHistory } from "react-router-dom";

export default function List() {
  const location = useLocation();
  const history = useHistory();
  const searchParams = qs.parse(location.search, { parseNumbers: true });

  const [sort, setSort] = useState(searchParams.sort || "desc");
  const [sortBy, setSortBy] useState(searchParams.sortBy || "id");
  const [page, setPage] = useState(searchParams.page || 0);

  useEffect(() => {
    const search = {
      sort,
      sortBy,
      page
    };
    history.replace({ search: qs.stringify(search, { arrayFormat: "comma" }) });
  }, [sort, sortBy, page, history]);

  const onChangePage = (event, newPage) => {
    setPage(newPage);
  };
  //similar for onChangeSort, onChangeSortBy

  return (
    <>
      ...
      <ListTableForm 
        page={page} 
        sort={sort} 
        sortBy={sortBy}
        onChangePage={onChangePage}
        // onChangeSort, onChangeSortBy
      />
    </>
  )
}

相关问题