【问题标题】:How to listen to localstorage in react.js如何在 react.js 中收听 localstorage
【发布时间】:2017-09-04 22:03:25
【问题描述】:

我在使用从本地存储中的数组获取数据的组件时遇到问题。它在页面加载时获取初始数据,但是当 localstorage 更改时如何更新?

import React, {Component} from 'react'; 
    class MovieList extends Component {
       constructor(props){
          super(props)
            this.state = {
            filmList: []     
          }
       }    
      componentWillMount(){
          var film = [],
          keys = Object.keys(localStorage),
          i = keys.length;
          while ( i-- ) {
             film.push( localStorage.getItem(keys[i]))     
          }
          this.setState({filmList: film})

      };

      render(){
        return(
           <ul>
              <li>{this.state.filmlist}</li>            
           </ul>

        );
    }

}

export default MovieList;

【问题讨论】:

  • 你无法真正听到本地存储的变化。当您更新本地存储值时,您应该发出一些事件来更新组件的状态。
  • 你如何更改本地存储。
  • @LeeHanKyeol 这听起来不错。我会试试的。
  • 我不确定如果 localStorage 值的更改源自与侦听器正在运行的同一选项卡,是否会触发该事件...
  • 有人找到解决方案了吗?我需要相同类型的解决方案。

标签: javascript reactjs localhost state


【解决方案1】:

对于遇到此问题的任何人,可以在此处找到“如何收听 localStorage 更改”的答案: https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent

【讨论】:

  • 总结:window.addEventListener('storage',e =&gt; console.log(e)) 然后在不同的选项卡中更改 localStorage
【解决方案2】:

根据 Mozilla 的 Web API 文档,只要对 Storage 对象进行更改,就会触发一个 StorageEvent

我在我的应用程序中创建了一个警报组件,只要对特定的localStorage 项目进行更改,该组件就会关闭。我会添加一个代码 sn-p 供您运行,但由于跨域问题,您无法通过它访问 localStorage。

class Alert extends React.Component {
    constructor(props) {
        super(props)
        this.agree = this.agree.bind(this)
        this.disagree = this.disagree.bind(this)
        this.localStorageUpdated = this.localStorageUpdated.bind(this)
        this.state = {
            status: null
        }
    }
    componentDidMount() {
        if (typeof window !== 'undefined') {
            this.setState({status: localStorage.getItem('localstorage-status') ? true : false})

            window.addEventListener('storage', this.localStorageUpdated)
        }
    }
    componentWillUnmount(){
        if (typeof window !== 'undefined') {
            window.removeEventListener('storage', this.localStorageUpdated)
        }
    }
    agree(){
        localStorage.setItem('localstorage-status', true)
        this.updateState(true)
    }
    disagree(){
        localStorage.setItem('localstorage-status', false)
        this.updateState(false)
    }
    localStorageUpdated(){
        if (!localStorage.getItem('localstorage-status')) {
            this.updateState(false)
        } 
        else if (!this.state.status) {
            this.updateState(true)
        }
    }
    updateState(value){
        this.setState({status:value})
    }
    render () {
        return( !this.state.status ? 
            <div class="alert-wrapper">
                <h3>The Good Stuff</h3>
                <p>Blah blah blah</p>
                <div class="alert-button-wrap">
                    <button onClick={this.disagree}>Disagree</button>
                    <button onClick={this.agree}>Agree</button>
                </div>
            </div>
         : null )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2019-11-01
    • 1970-01-01
    • 2020-07-25
    • 2012-03-07
    相关资源
    最近更新 更多