【问题标题】:REACT - using localstorage for updating a componentREACT - 使用本地存储来更新组件
【发布时间】:2020-08-27 23:42:06
【问题描述】:

如何通过更改另一个组件的本地存储来更新一个组件? 例如,使用 react hooks 我想通过更改 localstorage 值来调用函数,但不起作用:

React.useEffect(() => {
        //call a function by changing id value in localstorage
    }, [localStorage.getItem("id")])

【问题讨论】:

    标签: reactjs local-storage


    【解决方案1】:

    您需要使用 ContextProvider 在不同组件之间共享相同的钩子和数据。

    import React, { useContext, useEffect, useState } from 'react';
    
    import PropTypes from 'prop-types';
    
    const MyContext = React.createContext();
    
    const useMyHookEffect = (initId) => {
      const [id, setId] = useState(initId);
      const saveId = (id) => {
        window.localStorage.setItem('id', id);
        setId(id);
      };
    
      useEffect(() => {
        const myId = window.localStorage.setItem('id');
        setId(myId);
      }, []);
    
      return { id, saveId };
    };
    
    // Provider component that wraps app and makes themeMode object
    export function MyHookProvider({ children, id }) {
      const myEffect = useMyHookEffect(id);
      return (
        <MyContext.Provider value={myEffect}>
            {children}
        </MyContext.Provider>
      );
    }
    
    MyHookProvider.defaultProps = {
      children: null,
      id: null,
    };
    
    MyHookProvider.propTypes = {
      children: PropTypes.node,
      id: PropTypes.string,
    };
    
    export const useMyHook = () => useContext(MyContext);
    

    并且您需要将其称为组件之外的提供者。

    <MyHookProvider>
      <ComponentA />
      <ComponentB />
    </MyHookProvider>
    

    现在您可以在组件之间使用共享钩子了。

    export function ComponentA(){
      const { id, saveId } = useMyHook(null);
      return (<div>{id}<button onClick={() => saveId(2)}></button></div>);
    }
    

    【讨论】:

    • 谢谢,但我必须从反应外部发送一个值到反应组件。如何在反应之外设置 _id_in 上下文?
    • 你可以从你的钩子中导出函数。我已经更新了它。 @s.d.fard
    【解决方案2】:

    你可以使用window.addEventListener('storage ...


     React.useEffect(() => {
           function example() {
            //call a function by changing id value in localstorage
           }
           window.addEventListener('storage', example) 
           return () =>  window.removeEventListener('storage', example) 
          } , [ ])
    

    example 内,您可能会检查idlocalStorage 片段,使函数运行

    【讨论】:

    【解决方案3】:

    当你想重新渲染一个元素时,你应该使用状态。通过使用状态,每个使用此变量的元素都会自动更新。您可以使用钩子 useState()。

    import React, { useState, useEffect } from 'react';
    
    const [ id, setId ] = useState(initalValue);
    
    useEffect(() => {
        setId(localStorage.getItem('id'));
    }, [localStorage.getItem('id')]);
    
    return(
        'Your code and the element that should update'
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 2022-12-30
      • 2011-02-04
      • 2014-09-06
      • 2020-07-28
      • 2021-02-24
      相关资源
      最近更新 更多