我使用了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,和每一个过滤器
1条答案
按热度按时间uqcuzwp81#
应首先从searchParams获取页面、排序、搜索...的默认值
下面是我常用的代码: