yarn add react-cookies --dev
yarn add immutable --dev
测试代码:
import cookie from ‘react-cookies‘ // 导入对应库 import immutable from ‘immutable‘ const getStorage = (token)=>{ const json = {expire: token, data:{...token}} // 准备内容 window.localStorage.setItem(token, JSON.stringify(json)) // 本地存储数据, cookie.save(token, json) // 临时存储数据 const storage = immutable.fromJS(localStorage.getItem(token)) // 提取数据并转对象 const r_cookie = immutable.fromJS(cookie.load(token)) console.log(‘storage::‘,storage) console.log(‘storage JSON stringify:‘, JSON.stringify(storage)) console.log(‘storage JSON parse(...):‘, JSON.parse(storage)) //console.log(‘storage immutable.toJS():‘, storage.toJS()) //为什么要注释? 因为会报错,为什么要贴上来,为了分析错误! //console.log(‘storage immutable.getIn[]:‘, storage.getIn([‘expire‘])) //console.log(‘storage immutable.get()‘, storage.get(‘expire‘)) console.log(‘r_cookie::‘,r_cookie) console.log(‘r_cookie JSON stringify:‘, JSON.stringify(r_cookie)) console.log(‘r_cookie JSON parse(...):‘, JSON.parse(JSON.stringify(r_cookie))) console.log(‘r_cookie immutable.toJS():‘, r_cookie.toJS()) console.log(‘r_cookie immutable.getIn[]:‘, r_cookie.getIn([‘expire‘])) console.log(‘r_cookie immutable.get()‘, r_cookie.get(‘expire‘)) localStorage.clear() // 清理所有数据 localStorage.removeItem(token) // 清理指定数据 cookie.remove(token) // 清理指定数据 console.log(‘get:‘,localStorage.getItem(token),cookie.load(token)) }
如果storage无法存储对象,那如何调用immutable?可以先深解析后再通过immutable转换:
const json = {expire: token, data:{...token}} // 准备内容 window.localStorage.setItem(token, JSON.stringify(json)) // 本地存储数据, const storage = immutable.fromJS(JSON.parse(window.localStorage.getItem(token))) // 提取数据并转对象 console.log(‘storage immutable.toJS():‘, storage.toJS()) //为什么要注释? 因为会报错,为什么要贴上来,为了分析错误! console.log(‘storage immutable.getIn[]:‘, storage.getIn([‘expire‘])) console.log(‘storage immutable.get()‘, storage.get(‘expire‘))
这样也就可以与react-cookies结果一样,我们可以在浏览器中看到实际存储的token
这样基本存储token方法也就掌握了,但是怎么对比二者?目前我们知道localStorage与cookie区别一个永久存储一个临时存储!
根据上图我们知道storage只能存储字符串,如果存储对象则会报错!
React.JS详细分析token存储以及提取的方法,其中涉及技术(localStorage、react-cookies、immutable、JSON)
原文:https://www.cnblogs.com/eternalnight/p/14881958.html