最新消息:20181230 VPS服务器已从Linode换到腾讯云香港,主题仍用朋友推荐的大前端D8

【已解决】Reactjs中如何使用浏览器的localStorage或sessionStorage保存json即dict字典对象的值

JSON crifan 319浏览 0评论

折腾:

【已解决】内容管理系统的统计列表中只列当前组的用户

期间,对于目前使用:

      if (storedFunctionGroupNames === ‘undefined’) {

        const functionGroup = action.payload.function_group;

        const functionGroupOwner = action.payload.function_group_owner;

        const functionGroupIDs = action.payload.function_group_ids;

        const functionGroupFunctions = action.payload.function_group_functions;

        localStorage.setItem(‘functionGroupNames’, functionGroup.toString());

        localStorage.setItem(‘functionGroupOwners’, functionGroupOwner.toString());

        localStorage.setItem(‘functionGroupIDs’, functionGroupIDs.toString())

        localStorage.setItem(‘functionGroupFunctions’, functionGroupFunctions.toString())

        console.log("saveCurrentUser action.payload=", action.payload)

console中输出效果:

很明显,用了多个字符串的list的变量去保存到本地的localStorage中,

而别处再去用:

const functionGroupNames = localStorage.getItem(‘functionGroupNames’).split(‘,’);

const functionGroupOwners = localStorage.getItem(‘functionGroupOwners’).split(‘,’);

const functionGroupIDs = localStorage.getItem(‘functionGroupIDs’).split(‘,’);

let functionGroupId = ”;

去获取之前是字符串的值,现在用逗号分隔得到之前的list

显得很是麻烦。

希望去了解浏览器的本地存储,是否支持保存除了字符串之外的,比如json对象,dict对象的值

记得除了此处的localStorage,还有个sessionStorage

点击查看源码也看到了:

自己能想到的,最普通的做法是:

把json即dict,序列化为普通的json的字符串,

然后读取出来后,解析一下,应该就可以了

reactjs localstorage save json

Session Storage and Local Storage in React – RWieruch

JSON.parse(cachedHits)

JSON.stringify(result.hits)

javascript – Push JSON Objects to array in localStorage – Stack Overflow

应该是:

JSON.stringify(obj)

JSON.parse(str)

react redux – ReactJS: How do I pass data from JSON in local storage to a component? – Stack Overflow

Local storage with JSON parse and stringify

都是一样

然后先去改动服务器端返回的数据,再回来试试保存成json字符串

【已解决】Django中返回合并后的当前用户信息为JSON的字典对象

然后接着就可以去前端js中想办法保存json的dict对象的字符串了

【总结】

最后用代码保存:

      const foundSavedUser = localStorage.getItem(‘currentUser’)

      console.log("foundSavedUser=", foundSavedUser)

      if (!foundSavedUser) {

        const currentUser = action.payload.current_user;

        console.log("currentUser=", currentUser)

        if (currentUser) {

          const currentUserJsonStr = JSON.stringify(currentUser)

          console.log("currentUserJsonStr=", currentUserJsonStr)

          localStorage.setItem(‘currentUser’, currentUserJsonStr)

其中localStorage中的currentUser,保存的是json字符串,下面显示的是Chrome格式化后的效果。

然后用代码恢复:

    const restoredCurrentUserJsonStr = localStorage.getItem("currentUser")

    console.log("restoredCurrentUserJsonStr=", restoredCurrentUserJsonStr)

    if (restoredCurrentUserJsonStr){

      const restoredCurrentUser = JSON.parse(restoredCurrentUserJsonStr)

      console.log("restoredCurrentUser=", restoredCurrentUser)

    }

即可得到json的dict:

【后记】

后来看到:

javascript – Push JSON Objects to array in localStorage – Stack Overflow

去试试扩展已有Storage的方式

用:

src/utils/utils.js

Storage.prototype.setObj = function(strKey, objValue) {

  console.log("Storage.prototype.setOb: strKey=", strKey, ", objValue=", objValue)

  const jsonStr = JSON.stringify(objValue)

  console.log("jsonStr=", jsonStr)

  return this.setItem(strKey, jsonStr)

}

Storage.prototype.getObj = function(strKey) {

  console.log("Storage.prototype.getObj: strKey=", strKey)

  let parsedObj = undefined

  const storedStr = this.getItem(strKey)

  console.log("storedStr=", storedStr)

  if (storedStr) {

    parsedObj = JSON.parse(storedStr)

  }

  console.log("parsedObj=", parsedObj)

  return parsedObj

}

调用代码:

保存:

localStorage.setObj("currentUser", currentUser)

输出:

恢复:

passedOrRestoredCurrentUser = localStorage.getObj("currentUser")

输出:

即可达到方便调用的效果。

然后整理到自己的库中:

/*

* Javascript storage realted functions

*

* Crifan Li

* Updated: 20180731

*

*/

/*

  Save js object to local storage via json string

  call example: localStorage.setObj("currentUser", currentUser)

*/

Storage.prototype.setObj = function(strKey, objValue) {

  // console.log("Storage.prototype.setOb: strKey=", strKey, ", objValue=", objValue)

  const jsonStr = JSON.stringify(objValue)

  // console.log("jsonStr=", jsonStr)

  return this.setItem(strKey, jsonStr)

}

/*

  Restore js object from local storage’s stored json string

  call example: restoredCurrentUser = localStorage.getObj("currentUser")

*/

Storage.prototype.getObj = function(strKey) {

  // console.log("Storage.prototype.getObj: strKey=", strKey)

  let parsedObj

  const storedStr = this.getItem(strKey)

  // console.log("storedStr=", storedStr)

  if (storedStr) {

    parsedObj = JSON.parse(storedStr)

  }

  // console.log("parsedObj=", parsedObj)

  return parsedObj

}

最新代码详见:

https://github.com/crifan/crifanLib/tree/master/javascript

转载请注明:在路上 » 【已解决】Reactjs中如何使用浏览器的localStorage或sessionStorage保存json即dict字典对象的值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
59 queries in 0.099 seconds, using 9.48MB memory