我正在尝试使用 ES6 模板文字语法来设置 sessionStorage,其中键的一部分是事件选项卡 ID。
我首先尝试将 ES6 模板文字放入方法中:
sessionStorage.getItem(`tabContent + ${this.props.activeTabKey}`)
但这不会编译。
我接下来在我的方法中创建了一个常量,然后在 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))
我不确定什么是正确的语法,但都失败了并出现了错误:
SyntaxError: Unexpected token u in JSON at position 0
我的目标是有一种方法来动态检查存储以查看它们的 key 是否存在,如果不存在则进行设置。
除了高层次的理解外,我对 sessionStorage 不是很熟悉。我知道键和值必须是字符串。
我正在使用 React 和 Redux
最佳答案
Your error is likely a result of attempting to JSON.parse()
an undefined
value.
window.sessionStorage
可以结合JSON.stringify()
和 JSON.parse()
为 session 提交数据。
请参阅下面的实际示例,包括 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)
关于javascript - 如何使用 ES6 模板文字定义 sessionStorage 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49020293/