javascript - 如何在 react.js 中监听 localstorage

标签 javascript reactjs localhost state

我在使用从本地存储中的数组获取数据的组件时遇到问题。它在页面加载时获取初始数据,但是当 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;

最佳答案

根据 Mozilla 的 Web API 文档,有一个 StorageEvent 会在 Storage 对象发生更改时触发。

我在我的应用程序中创建了一个警报组件,只要对特定的 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 )
    }
}

关于javascript - 如何在 react.js 中监听 localstorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43313372/

相关文章:

javascript - 如何创建一个 Windows Phone 应用程序来解析网站中的 html 数据

javascript - 如何在React中使用formik创建动态下拉菜单?

javascript - 在 reactjs 中设置 componentDidMount 间隔是一种正确的方法吗?

mysql - 如何快速将大型 CSV 文件导入数据库

css - 在拥有托管站点时调用样式表

asp.net - 本地主机找不到存储过程 'dbo.aspnet_CheckSchemaVersion'

javascript - 如何测试指令中属性的存在?

javascript - jQuery 干扰 javascript 搜索功能(传递参数)

javascript - isNaN JavaScript 函数

JavaScript ecma 6 批量导入