【发布时间】:2018-06-05 10:49:20
【问题描述】:
我一直在为我的项目使用 react。现在我正在尝试使用 localStorage 作为我的主存储,因为除了 algolia 之外没有任何数据库连接。
但是当我尝试在这行代码中访问我的本地存储时,我的 localStorage 代码现在未通过其他测试(渲染测试等)并得到“TypeError: Cannot read property 'getItem' of undefined”:
var collections = JSON.parse(window.localStorage.getItem('collections'));
我猜这是因为我试图创建一个组件,但 localStorage 仍然未定义(或尚未定义)
这是我定义本地存储的代码
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Header from '../../components/header/header';
import Footer from '../../components/footer/footer';
import RecommendedCategory from '../../components/recommendedCategory/recommendedCategory';
import RecommendedItem from '../../components/recommendedItem/recommendedItem';
import './css/home.css';
class Home extends Component {
render() {
var collections, urlCollections;
if(window.localStorage.collections === undefined || window.localStorage.urlCollections === undefined){
collections = [];
urlCollections = [];
} else {
collections = JSON.parse(window.localStorage.getItem('collections'));
urlCollections = JSON.parse(window.localStorage.getItem('urlCollections'));
}
window.localStorage.setItem('collections', JSON.stringify(collections));
window.localStorage.setItem('urlCollections', JSON.stringify(urlCollections));
return (
<BrowserRouter>
<div className="Home">
<Header />
<div className="containerCategory">
<RecommendedCategory />
<RecommendedItem />
</div>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default Home;
您知道如何在不通过渲染测试的情况下在 localStorage 中获取项目吗?
【问题讨论】:
-
你在运行单元测试吗? (没有真正的浏览器)
-
这个question的副本
标签: reactjs local-storage