簡體   English   中英

如何在 react.js 中監聽 localstorage

[英]How to listen to localstorage in 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;

根據Mozilla的Web API文檔,只要對Storage對象進行了更改,就會觸發一個StorageEvent

我在我的應用程序中創建了一個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 )
    }
}

對於任何絆倒這個問題的人,可以在這里找到“如何收聽localStorage更改”的答案: https//developer.mozilla.org/en-US/docs/Web/API/StorageEvent

import React, { Component } from "react";
import { Subject, share } from "rxjs";

export default class StorageService extends Component {
  constructor() {
    super();
    this.start();
    this.onSubject = new Subject();
    this.changes = this.onSubject.asObservable().pipe(share());
  }

  componentWillUnmount() {
    this.stop();
  }

  getStorage() {
    let s = [];
    for (let i = 0; i < localStorage.length; i++) {
      s.push({
        key: localStorage.key(i),
        value: JSON.parse(localStorage.getItem(localStorage.key(i))),
      });
    }
    return s;
  }

  store(key, data) {
    localStorage.setItem(key, JSON.stringify(data));
    this.onSubject.next({ key: key, value: data });
  }

  clear(key) {
    localStorage.removeItem(key);
    this.onSubject.next({ key: key, value: null });
  }

  start() {
    window.addEventListener("storage", this.storageEventListener.bind(this));
  }

  storageEventListener(event) {
    if (event.storageArea === localStorage) {
      let v;
      try {
        v = JSON.parse(event.newValue);
      } catch (e) {
        v = event.newValue;
      }
      this.onSubject.next({ key: event.key, value: v });
    }
  }

  stop() {
    window.removeEventListener("storage", this.storageEventListener.bind(this));
    this.onSubject.complete();
  }

  render() {
    return <div>StorageService</div>;
  }
}

// 在你需要的地方導入它並訂閱


const newStorageService = new StorageService();
newStorageService.changes.subscribe((localStoreObject) => {
    // do whatever yo want 
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM