【问题标题】:Is there a way to loadFromLocalStorage and saveToLocalStorage in one useEffect hook?有没有办法在一个 useEffect 挂钩中加载FromLocalStorage 和 saveToLocalStorage?
【发布时间】:2019-05-25 17:46:18
【问题描述】:

我设法在我的功能组件中使用 2 个 useEffect 钩子来完成这项工作”:

  useEffect(() => {
    console.log('LOAD_FROM_LOCALSTORAGE')
    loadFromLocalStorage({ dispatch })
  }, [])

  useEffect(
    () => {
      console.log('SAVE_TO_LOCALSTORAGE')
      saveToLocalStorage(state)
    },
    [state]
  )

有一个 egghead.io tutorial 关于如何使用 localStorageuseState 钩子,但我使用的是 useContextuseReducer 用于应用状态管理。

这是我的 loadFromLocalStorage 函数:

const loadFromLocalStorage = async ({ dispatch }) => {
  try {
    const serializedState = await localStorage.getItem('state')
    if (serializedState === null) return undefined
    const persistedState = await JSON.parse(serializedState)
    await dispatch({ type: 'LOAD_FROM_LOCALSTORAGE', persistedState })
  } catch (e) {
    console.log(e)
    return undefined
  }
}

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    我认为合并这两种效果没有什么好处 - 它们现在很干净并且正在做他们应该做的事情,但你可以尝试类似的事情

    const [state, dispatch] = useReducer(reducerFunction, {});
    
    useEffect(
        () => {
            // if there is no state 
            if(!Object.keys(state).length) {
                loadFromLocalStorage({ dispatch })
                return;
            }
            saveToLocalStorage(state)
        },
        [state]
    )
    

    【讨论】:

      猜你喜欢
      • 2014-06-22
      • 1970-01-01
      • 2020-03-09
      • 2021-12-03
      • 2021-05-14
      • 2012-01-18
      • 1970-01-01
      相关资源
      最近更新 更多