我试图在页面重新加载时不丢失我的 state
值,该值是 cart
。我可以在任何页面将任何 product
添加到我的 cart
中,但每当我重新加载页面时,cart
状态就会重置。有没有办法在使用或不使用更多库的情况下防止这种情况发生?我不知道是否只有使用 Redux
才能防止这种情况。
我的 App
函数:
function App() {
const [cart, setCart] = useState([]);
return (
<div>
<Router>
<NavbarComponent cart = {cart} setCart={setCart}></NavbarComponent>
<Switch>
<Route exact path="/">
<Home cart = {cart} setCart={setCart} />
</Route>
<Route exact path="/home">
<Home cart = {cart} setCart={setCart} />
</Route>
<Route exact path="/Products">
<Products cart = {cart} setCart={setCart} />
</Route>
<Route exact path="/Detail/:product_id">
<Detail cart = {cart} setCart={setCart} ></Detail>
</Route>
</Switch>
</Router>
</div>
);
}
以下是我可以改变 cart
状态值的组件之一。
export function CardComponent(props) {
const { cart, products, setCart } = props;
//const products = props.products;
const addToCart = (product) => {
let tempCart = [...cart]
tempCart.push(product);
setCart(tempCart)
console.log(cart);
};
return (
<div className="container cards">
<div className="featured">
Featured Products
{cart.length}
<div className="featured-underline"></div>
</div>
<CardColumns>
{products.map((product, index) => {
if (product.is_featured)
return (
<Card key={index}>
<CardImg
top
width="100%"
src="https://dl.airtable.com/.attachmentThumbnails/5ebc46a9e31a09cbc6078190ab035abc/8480b064"
alt="Card image cap"
/>
<CardBody>
<CardTitle tag="h5">{product.name}</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
Card subtitle
</CardSubtitle>
<CardText>{product.description}</CardText>
<Button onClick={() => addToCart(product)} color="primary">
Add to cart
</Button>
<Button color="info ml-2">Detail</Button>
<p style={{ float: "right", color: "brown" }}>
${product.price}
</p>
</CardBody>
</Card>
);
else return;
})}
</CardColumns>
</div>
);
}