简体   繁体   English

如何使用 React 钩子检查 localStorage 是否为空?

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

This is a continuation of another question I asked, Adding/deleting data into local browser storage using a button, and displaying it in a UI table (React)这是我问的另一个问题的延续, 使用按钮将数据添加/删除到本地浏览器存储中,并将其显示在 UI 表中 (React)

I am trying to check localStorage and use an emitter to tell the console if localStorage is empty of any values.我正在尝试检查 localStorage 并使用发射器告诉控制台 localStorage 是否没有任何值。

I believe I have 2 issues.我相信我有两个问题。

  1. The App needs to check localStorage when it is initialized (when browser is opened) App初始化时需要检查localStorage(浏览器打开时)
  2. I need to use useState, so that the localStorage is checked every time a value is added/deleted我需要使用useState,以便每次添加/删除值时检查localStorage

Below is my attempt (index.js):以下是我的尝试(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'));

I made a function checkLocalStorage() that should be called every time a value is added, or deleted:我创建了一个函数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');
}

But it is not working as I expect.但它并没有像我预期的那样工作。 What will happen is:将会发生的事情是:

  1. I start the React App (console does not say "Local storage is empty")我启动了 React 应用程序(控制台没有说“本地存储为空”)
  2. I submit a value, console says, "Local storage is empty"我提交了一个值,控制台显示“本地存储为空”
  3. I refresh the browser, and "Local storage is empty" message disappears我刷新浏览器,“本地存储为空”消息消失
  4. If I add another value again, same process occurs.如果我再次添加另一个值,则会发生相同的过程。

What SHOULD happen (if starting with empty localStorage):应该发生什么(如果从空的 localStorage 开始):

  1. I start the React App (console says "Local storage is empty")我启动 React 应用程序(控制台显示“本地存储为空”)
  2. I submit a value (only one value present), no message to console我提交了一个值(仅存在一个值),控制台没有消息
  3. I refresh page and still no console message我刷新页面,仍然没有控制台消息
  4. I delete a value, "Local storage is empty" message appears in console我删除了一个值,控制台中出现“本地存储为空”消息

I believe I am not using React hooks properly, I initialized the hook:我相信我没有正确使用 React 钩子,我初始化了钩子:

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

I then try to use it like this inside const App :然后我尝试在const App像这样使用它:

checkLocalStorage(setLocalValue)

I am not sure, what I am doing wrong, like I said before, I think I am not using hooks correctly, if more information is needed, please let me know.我不确定,我做错了什么,就像我之前说的,我认为我没有正确使用钩子,如果需要更多信息,请告诉我。

You can use "onstorage" event to check when it updates.您可以使用“ontorage”事件来检查它何时更新。 For example on root of your app:例如在您的应用程序的根目录上:

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