如何在react.js中收听localstorage

jer*_*eph 7 javascript state localhost reactjs

我遇到了一个从localstorage中的数组中获取数据的组件的问题.它在页面加载时获取初始数据,但是当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;
Run Code Online (Sandbox Code Playgroud)

Jos*_*eso 10

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

我在我的应用程序中创建了一个Alert组件,只要对特定localStorage项目进行了更改,它就会消失.我会添加一个代码片段供您运行,但由于跨源问题,您无法通过它访问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 )
    }
}
Run Code Online (Sandbox Code Playgroud)


mez*_*zod 6

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

  • 摘要:`window.addEventListener('storage',e =&gt; console.log(e))` 然后在不同的选项卡中更改 localStorage (2认同)