简体   繁体   中英

How to listen sessionStorage in react js?

I want to listen to every change inside SessionStorage . Is there a way to listen to it whenever it has changed? I'm using react classes.

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>
    );
  }
}

You could do

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

remember to unmount the listener

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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