2017-04-10 32 views
1

我在從localstorage中的數組獲取數據的組件中遇到問題。它在頁面加載時獲取初始數據,但在本地存儲更改時如何更新?如何在react.js中監聽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; 
+1

你真的不能聽localStorage的變化。在更新本地存儲值時,應該發出一些事件來更新組件的狀態。 –

+0

你如何改變本地存儲。 –

+0

@ LeeHanKyeol這聽起來很不錯。我會嘗試。 –

回答

2

每Mozilla的網頁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) 
    } 
}