我的Next.js应用程序有这些动态页面:products/[category]/[subcategory]
。它们都使用相同的组件-ProductsList
,具有排序功能。我更新了此组件中sortingWay
的状态,以便在这些页面之间路由。
从下一个文档:
当导航到Next.js中的同一页面时,默认情况下不会重置页面的状态,因为react不会卸载,除非父组件已更改。
它工作正常,但是当sortingWay
有值并且我刷新页面时,它会重置状态。我试图将sortingWay
保留在localStorage
中,它不工作。[category].js
([subcategory].js
几乎相同)
import { useRouter } from 'next/router';
import ProdList from '../../../components/ProdList';
import React from "react";
export default function SubCategory({ products }) {
const router = useRouter();
const category = router.query.category;
const filtered = products.filter(product => category === product.category);
return (
<>
<h1>Товари підкатегорії {category}</h1>
<ProdList data={filtered}/>
</>
)
}
export async function getStaticProps() {
const response = await fetch(`http://localhost:4000/products`);
const data = await response.json();
return {
props: {
products: data
}
}
}
export async function getStaticPaths() {
const response = await fetch('http://localhost:4000/products');
const data = await response.json();
const paths = data.map(product => {
return {
params: {
category: product.category,
},
}
})
return {
paths,
fallback: false
}
}
ProductList.jsx
组件
import React from 'react'
import { useEffect, useState } from "react";
import { useRouter } from 'next/router';
import ProductItem from '../ProductItem';
import { productList } from './styles';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
export default function ProdList({ data }) {
const [ sortingWay, setSortingWay ] = useState('');
const [ productsList, setProductList ] = useState(data);
const router = useRouter();
const { pathname, query } = router
const category = router.query.category;
const subCategory = router.query.subCategory;
useEffect(() => {
setSortingWay('')
}, [router.query.subCategory])
useEffect(() => {
setProductList(data)
}, [router.query.category, router.query.subCategory])
useEffect(() => {
addEventListener('beforeunload', event => {
const data = window.localStorage.getItem('sorting___Way');
if(data.length > 0 ) setSortingWay(data) ;
})
}, []);
useEffect(() => {
window.localStorage.setItem('sorting___Way', sortingWay);
setSortingWay(sortingWay)
}, [sortingWay]);
// sorting
const calcSalePrice = (price, sale) => {
const normalized = parseInt(price.replace(/\s+/g, ''));
return (normalized / 100) * (100 - sale);
}
const sortByPriceAscending = () => {
return data.sort((a, b) => {
const priceA = calcSalePrice(a.price, a.sale);
const priceB = calcSalePrice(b.price, b.sale);
return priceA - priceB;
})
}
const sortByPriceDescending = () => {
return data.sort((a, b) => {
const priceA = calcSalePrice(a.price, a.sale);
const priceB = calcSalePrice(b.price, b.sale);
return priceB - priceA;
})
}
const sortBySale = () => data.sort((a, b) => b.sale - a.sale);
const sortByDefault = () => data.sort((a, b) => a.id - b.id);
// https://nextjs.org/docs/routing/shallow-routing
const shallowRoute = (targetValue) => {
if (category && !subCategory) {
return router.push(`/prod/${category}/?sortBy=${targetValue}`, undefined, { shallow: true })
} else if (category && subCategory) {
return router.push(`/prod/${category}/${subCategory}/?sortBy=${targetValue}`, undefined, { shallow: true })
}
}
// handler
const handleChange = ({ target }) => {
const { value } = target;
if (value === "asc") {
setProductList(sortByPriceAscending());
} else if (value === "des") {
setProductList(sortByPriceDescending());
} else if (value === "sale") {
setProductList(sortBySale());
} else if (value === "default") {
setProductList(sortByDefault());
}
setSortingWay(value);
shallowRoute(value)
}
return (
<div>
<FormControl variant="standard" sx={{ m: 1, minWidth: 120 }}>
<InputLabel id="sort-products-label">Сортувати</InputLabel>
<Select
labelId="sort-products-label"
id="sort-products"
value={sortingWay}
label="Сортувати"
onChange={handleChange}
>
<MenuItem value={"asc"}>За зростанням ціни</MenuItem>
<MenuItem value={"des"}>За спаданням ціни</MenuItem>
<MenuItem value={"sale"}>За знижками</MenuItem>
<MenuItem value={"default"}>За замовчуванням</MenuItem>
</Select>
</FormControl>
<div>
{
productsList.map(product =>
<ProductItem
key={product.id}
id={product.id}
subCategory={product.subCategory}
title={product.title}
price={product.price}
image={product.image}
sale={product.sale}
/>
)
}
</div>
</div>
)
}
1条答案
按热度按时间ojsjcaue1#
不论任何其他问题;
看起来您只获取了
beforeunload
上的数据。