首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在React中,我希望在刷新页面之后保持状态。

在React中,我希望在刷新页面之后保持状态。
EN

Stack Overflow用户
提问于 2022-09-13 14:36:15
回答 2查看 55关注 0票数 0

在React中,我想在刷新页面之后保持状态。我试图使用localStorage,但每次刷新页面时,它都会清除数据。

代码语言:javascript
复制
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>
    </>

  );
}
EN

回答 2

Stack Overflow用户

发布于 2022-09-13 14:39:13

您能否首先检查这些项目是否保存在本地存储区?

运行应用程序->转到控制台->应用程序->本地存储

你能在那里看到任何数据吗?

票数 0
EN

Stack Overflow用户

发布于 2022-09-13 15:20:18

改变

代码语言:javascript
复制
const [cart, setCart] = useState([])

代码语言:javascript
复制
const [cart, setCart] = useState(localStorage.getItem("cart-item") ?  JSON.parse(localStorage.getItem("cart-item")) : [])

应该能正常工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73704855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档