我在导航栏中的父应用程序中设置了一个状态,然后将其传递给子组件。点击状态会传递,然后在刷新页面时不再设置。
App(设置状态的父级)
const [brand, setBrand] = useState("");
const brandSet = (value) => {
setBrand(value);
};
return (
<div>
<NavBar
login={login}
logout={logout}
auth={auth}
createAccount={createAccount}
brandSet={brandSet}
/>
<Route
path="/products:brand"
render={() => (
<BrandProducts
products={products}
productVariants={productVariants}
brand={brand}
addToCart={addToCart}
brandSet={brandSet}
/>
)}
/>
导航栏
const NavBar = ({ logout, login, auth, createAccount, brandSet }) => {
return (
<div>
{auth.id ? (
<Navbar bg="light" expand="lg">
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/#/about">About Us</Nav.Link>
<NavDropdown title="Brands" id="basic-nav-dropdown">
<NavDropdown.Item href="/#/products">
All Products
</NavDropdown.Item>
<NavDropdown.Item
href="/#/products:PoloRalphLauren"
onClick={() => brandSet("Polo Ralph Lauren")}
>
Polo Ralph Lauren
</NavDropdown.Item>
<NavDropdown.Item
href="/#/products:TommyHilfiger"
onClick={() => brandSet("Tommy Hilfiger")}
>
Tommy Hilfiger
</NavDropdown.Item>
品牌产品(查看)
const BrandProducts = ({ products, productVariants, addToCart, brand }) => {
const brandProds = products.filter((product) => {
return product.brand === brand;
});
return (
<Container className="mt-5">
<Row>
<h2>All {brand}</h2>
</Row>
<Row>
{brandProds.map((product) => {
return (
<Col md={3} className="list-unstyled" key={product.id}>
<Product
key={product.id}
product={product}
addToCart={addToCart}
productVariants={productVariants}
/>
</Col>
);
})}
</Row>
</Container>
);
};
不能持续的状态是brand
中的BrandProducts
,在此先感谢您的帮助!
答案 0 :(得分:0)
默认情况下,页面刷新不会持久存在。您可以实施自己的缓存解决方案,也可以使用现有的缓存解决方案,例如https://www.npmjs.com/package/use-persisted-state