在React中,我想在刷新页面之后保持状态。我试图使用localStorage,但每次刷新页面时,它都会清除数据。
function App() {
const [selected, setSelected] = useState()
const [cart, setCart] = useState([])
const items = [
{
name: "xx99 mark || headphones",
description: "This huge e-commerce challenge will provide an incredible test for your front-end skills. Once you're done, you'll have an amazing project to add to your portfolio!",
img: "https://images.pexels.com/photos/205926/pexels-photo-205926.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
price: 159
},
{
name: "xx99 mark | headphones",
description: "This huge e-commerce challenge will provide an incredible test for your front-end skills. Once you're done, you'll have an amazing project to add to your portfolio!",
img: "https://images.pexels.com/photos/610945/pexels-photo-610945.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
price: 120,
},
{
name: "x99 mark || headphones",
description: "This huge e-commerce challenge will provide an incredible test for your front-end skills. Once you're done, you'll have an amazing project to add to your portfolio!",
img: "https://images.pexels.com/photos/3945667/pexels-photo-3945667.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
price: 400
},
]
localStorage.setItem("cart-item", JSON.stringify(cart))
return (
<>
<userContext.Provider value={{ selected, setSelected, items, cart, setCart }}>
<BrowserRouter>
<Navbar />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/headphones' element={<Headphones />} />
<Route path='/speakrs' element={<Speakers />} />
<Route path='/earphones' element={<Earphones />} />
<Route path='/cart' element={<Cart />} />
</Routes>
</BrowserRouter>
</userContext.Provider>
</>
);
}发布于 2022-09-13 14:39:13
您能否首先检查这些项目是否保存在本地存储区?
运行应用程序->转到控制台->应用程序->本地存储
你能在那里看到任何数据吗?
发布于 2022-09-13 15:20:18
改变
const [cart, setCart] = useState([])至
const [cart, setCart] = useState(localStorage.getItem("cart-item") ? JSON.parse(localStorage.getItem("cart-item")) : [])应该能正常工作。
https://stackoverflow.com/questions/73704855
复制相似问题