2017-04-10 8 views
1

localstorageの配列からデータを取得するコンポーネントに問題があります。ページの読み込み時に初期データを取得しますが、localstorageが変更されたときにどのように更新すればよいですか? MozillaのウェブAPIドキュメント毎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

変更がStorageオブジェクトに対して行われるたびにトリガーされますStorageEventがあります。

特定の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) 
    } 
} 
関連する問題