简体   繁体   English

无法从ComponentWillMount的sessionStorage中获取项目?

[英]Cannot getItem from sessionStorage in ComponentWillMount?

Just looking to pull in some data sitting in sessionStorage inside of componentWillMount but I continue running into: cannot getItem of undefined . 只是想获取一些位于componentWillMount内的sessionStorage中的数据,但我继续cannot getItem of undefinedcannot getItem of undefined Here is what this looks like: 看起来是这样的:

  componentWillMount() {
    console.log(window.sessionStorage); // logs sessionStorage
    console.log(window.sessionStorage.getItem('some-key')); // errors out here
  }

EDIT: Here is a screenshot. 编辑:这是一个屏幕截图。 The key is different because I was just using something else for the example, but the error is the same. 关键是不同的,因为我只是在示例中使用其他内容,但是错误是相同的。

在此处输入图片说明

Here is the error: TypeError: Cannot read property "getItem" from undefined . 这是错误: TypeError: Cannot read property "getItem" from undefined Odd enough, it works in componentDidMount . 奇怪的是, 它可以在componentDidMount中使用

For clarification: I'm using window.sessionStorage instead of sessionStorage because for some reason it can't recognize it without appending it to the window object. 为了澄清:我使用window.sessionStorage而不是sessionStorage因为由于某种原因,如果不将其附加到window对象,它将无法识别它。

Found one or two other questions on similar topics but nothing to help explain why getItem is not available on sessionStorage . 在类似主题上发现了另外一个或两个问题 ,但没有任何帮助来解释为什么getItemsessionStorage上不可用。

您可以在ComponentDidMount使用sessionStorage

Add this method to your component class(.ts file). 将此方法添加到您的组件类(.ts文件)。

get sessionStorage() {
    return sessionStorage;
}

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

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