简体   繁体   English

如何在定义 sessionStorage 键时使用 ES6 模板文字

[英]How to use ES6 template literal in defining sessionStorage key

I am trying to use ES6 template literal syntax to set sessionStorage where part of the key is the active tab id.我正在尝试使用 ES6 模板文字语法来设置 sessionStorage,其中键的一部分是活动选项卡 ID。

I attempted first to put the ES6 template literal within the method:我首先尝试将 ES6 模板文字放在方法中:

sessionStorage.getItem(`tabContent + ${this.props.activeTabKey}`)

But this wouldn't compile.但这不会编译。

I next created a constant within my method and then referred to it within the sessionStorage method:我接下来在我的方法中创建了一个常量,然后在 sessionStorage 方法中引用它:

//attempt 1
const activeTabSessionStorageName = `tabContent + ${this.props.activeTabKey}`
(sessionStorage.getItem(`${activeTabSessionStorageName}`))

// attempt 2

const activeTabSessionStorageName = `tabContent + ${this.props.activeTabKey}`

  sessionStorage.getItem(JSON.stringify(activeTabSessionStorageName))

//attempt 3
const activeTabSessionStorageName = `tabContent + ${this.props.activeTabKey}`
(sessionStorage.getItem(this.activeTabSessionStorageName))

I am not sure what would be the correct syntax but both failed and came up with the error:我不确定什么是正确的语法,但都失败了并出现了错误:

 SyntaxError: Unexpected token u in JSON at position 0

My goal is to have a way to dynamically check the storage to see if they key exists and then set it if not.我的目标是有一种方法来动态检查存储以查看它们是否存在,如果不存在则设置它。

I am not that familiar with sessionStorage other than high level understanding.除了高级别的理解之外,我对 sessionStorage 不太熟悉。 I know the key and the value have to be strings.我知道键和值必须是字符串。

I am using React and Redux我正在使用 React 和 Redux

Your error is likely a result of attempting to JSON.parse() an undefined value. 您的错误可能是由于尝试JSON.parse() undefined值造成的。

window.sessionStorage can be combined with JSON.stringify() and JSON.parse() to commit data for sessions. window.sessionStorage可以与JSON.stringify()JSON.parse()结合起来为会话提交数据。

See below for a practical example, including Template Literals and a safe escape for cases when no sessionStorage Item is found.请参阅下面的实际示例,包括Template Literals和未找到sessionStorage Item情况下的安全转义。

// Hypothetical Object.
const hypotheticalObject = {
  id: 'unique id',
  data: 'data ..'
}

// Set Object to Session Storage.
window.sessionStorage.setItem(`CONTENT + ${hypotheticalObject.id}`, JSON.stringify(hypotheticalObject))

// Get Object.
const retrievedObject = window.sessionStorage.getItem(`CONTENT + ${hypotheticalObject.id}`) && JSON.parse(window.sessionStorage.getItem(`CONTENT + ${hypotheticalObject.id}`)) || false

// Log.
console.log(retrievedObject)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM