gpt4 book ai didi

javascript - ReactJS如何在刷新页面时保持状态值

转载 作者:行者123 更新时间:2023-12-04 11:30:11 26 4
gpt4 key购买 nike

我尽量不丢失我的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>
);
}

最佳答案

数据必须以某种方式持续存在 - 这意味着您必须将其实际保存在某个地方。
您可以在客户端上使用 localStorage。然后只需确保在购物车更改时对其进行更新。
就像是:

  const [cart, setCart] = useState(localStorage.getItem('cart'));

useEffect(()=>{
localStorage.setItem('cart', cart)
},[cart]);
文档:
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
  • https://reactjs.org/docs/hooks-effect.html
  • 关于javascript - ReactJS如何在刷新页面时保持状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65231494/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com