簡體   English   中英

如何使用 React 鈎子檢查 localStorage 是否為空?

[英]How to check if localStorage is empty with React hooks?

這是我問的另一個問題的延續, 使用按鈕將數據添加/刪除到本地瀏覽器存儲中,並將其顯示在 UI 表中 (React)

我正在嘗試檢查 localStorage 並使用發射器告訴控制台 localStorage 是否沒有任何值。

我相信我有兩個問題。

  1. App初始化時需要檢查localStorage(瀏覽器打開時)
  2. 我需要使用useState,以便每次添加/刪除值時檢查localStorage

以下是我的嘗試(index.js):

import React,{useState} from 'react';
import ReactDOM from 'react-dom';
const EventEmitter = require('events');

const useStateWithLocalStorageArray = localStorageKey => {
  const [value, setValue] = React.useState(
    JSON.parse(localStorage.getItem(localStorageKey) || '[]' )
  );
  React.useEffect(() => {
    localStorage.setItem(localStorageKey, JSON.stringify(value))
  }, [value]);
  return [value, setValue];
};

const checkLocalStorage = function() {
  const myEmitter = new EventEmitter();
  myEmitter.on('event', () => {
    if (localStorage.getItem('customKey1') === '[]') {
      console.log('Local storage is empty');
    }
  });
  return myEmitter.emit('event');
}

const App =()=>{
  const [items,setItems] = useStateWithLocalStorageArray('customKey1')
  const [value,setValue] = useState({NAME:'',AGE:'',SALARY:''})
  const [localValue, setLocalValue] = useState('')


  const updateValue = e =>{
     setValue({...value,[e.target.id]:e.target.value})
  }


  return(
    <div>
      <div>
        <input value={value.NAME} id='NAME' placeholder='Name' onChange={(e)=>updateValue(e)}/>
        <input value={value.AGE } id='AGE' placeholder='Age' onChange={(e)=>updateValue(e)}/>
        <input value={value.SALARY} id='SALARY' placeholder='Salary' onChange={(e)=>updateValue(e)}/>
      <button onClick={()=>{
        setItems([...items,{...value}])
        setValue({NAME:'',AGE:'',SALARY:''})
        checkLocalStorage(setLocalValue)
        }}>ADD ITEM</button></div>

      <br/>
      <div>List of Items</div>
      <br/>
      { items &&
      <div>
        {
            items.map((item,index)=>(
              <li key={index}>{item.NAME}-{item.AGE}-{item.SALARY} <button onClick={()=>{
                setItems(items.filter((value,iindex) => iindex !== index))
                checkLocalStorage(setLocalValue)
              }}>Remove</button> </li>
            ))
        }
      </div>
    }
    </div>
  )
}

ReactDOM.render(<App/>, document.getElementById('root'));

我創建了一個函數checkLocalStorage() ,每次添加或刪除值時都應該調用它:

const checkLocalStorage = function() {
  const myEmitter = new EventEmitter();
  myEmitter.on('event', () => {
    if (localStorage.getItem('customKey1') === '[]') {
      console.log('Local storage is empty');
    }
  });
  return myEmitter.emit('event');
}

但它並沒有像我預期的那樣工作。 將會發生的事情是:

  1. 我啟動了 React 應用程序(控制台沒有說“本地存儲為空”)
  2. 我提交了一個值,控制台顯示“本地存儲為空”
  3. 我刷新瀏覽器,“本地存儲為空”消息消失
  4. 如果我再次添加另一個值,則會發生相同的過程。

應該發生什么(如果從空的 localStorage 開始):

  1. 我啟動 React 應用程序(控制台顯示“本地存儲為空”)
  2. 我提交了一個值(僅存在一個值),控制台沒有消息
  3. 我刷新頁面,仍然沒有控制台消息
  4. 我刪除了一個值,控制台中出現“本地存儲為空”消息

我相信我沒有正確使用 React 鈎子,我初始化了鈎子:

const [localValue, setLocalValue] = useState('')

然后我嘗試在const App像這樣使用它:

checkLocalStorage(setLocalValue)

我不確定,我做錯了什么,就像我之前說的,我認為我沒有正確使用鈎子,如果需要更多信息,請告訴我。

您可以使用“ontorage”事件來檢查它何時更新。 例如在您的應用程序的根目錄上:

window.addEventListener('storage', event => {
  // event contains
  // key – the key that was changed
  // oldValue – the old value
  // newValue – the new value
  // url – 
  // storageArea – either localStorage or sessionStorage object where the update happened.
});
const useStorage = (storageName) => {

  const checkStorage = key => {
     const storedData = localStorage.getItem(key);
     if (!storedData) console.log('Local storage is empty');
  }

  useEffect(() => {
   // when app loaded
   checkStorage(storageName)

    // when storage updated
    const handler = ({key}) => checkStorage(key);
    window.addEventListener('storage', handler);
    retunr () => window.removeEventListener('storage', handler);
  }, []);
}

暫無
暫無

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

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