繁体   English   中英

如何在 React js 中监听 sessionStorage?

[英]How to listen sessionStorage in react js?

我想听听SessionStorage中的每一个变化。 有没有办法在它改变时听它? 我正在使用反应类。

class Module extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      ....
    };
  }


  handleClick(e) {
    const value = e.currentTarget.textContent;
    sessionStorage.setItem("AnyValue", value);
  }

  render() {
    return (
      <div
        onClick={this.handleClick}
      >
        {this.props.id}
      </div>
    );
  }
}

你可以做

componentDidMount() {
  window.addEventListener('storage', () => {
    console.log("CHANGED!!!");    
  });
}

记得卸载监听器

componentWillUnmount() {
  window.removeEventListener('storage');
}

暂无
暂无

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

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