【问题标题】:Using Redux default store from window in React app在 React 应用程序的窗口中使用 Redux 默认存储
【发布时间】:2021-11-30 10:19:57
【问题描述】:

我有一个从本地存储收集用户保存信息的 React Web 应用程序。首先,我将保存的信息检索到window.store。我可以在控制台中看到window.store 在那里。但它总是给出未定义的错误。我试图让睡眠,以便在睡眠后,存储可以从全局窗口对象获取数据。

init.js

const InitializeApp = () => {
    let [getState, setState] = useState(false)
    useEffect(()=>{
        const asyncState = async() => {
            let store = await loadFromStorage()
            window.store = store
            await sleep(5000)
            console.log(store);
            setState(true)
        }
        asyncState()
    },[])
    if(!getState){
        return(
            <InitTemplate />
        )
    }else{
        return(
            <Main />
        )
    }
}

App.js

const Main = () => {
  return(
    <Provider store={Store}>
      <App />
    </Provider>
  );
}

store.js

const AppReducer = (state = window.store , action) => {
    switch(action.type){
        default :
            return state;
    }
}

问题是每当我使用useSelector() 时,我都会收到undefined。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript reactjs redux local-storage


    【解决方案1】:

    显然您正在尝试将状态保存到localStorage 并在重新加载页面后加载它

    我认为您在从localeStorage加载状态时不需要创建Promise

    尝试初始化store如下图

    store.js

    import {createStore} from "redux";
    import AppReducer from "./AppReducer";
    
    export const loadState = () => {
        try {
            const state = localStorage.getItem('state');
            if (state === null) {
                return undefined;
            }
            return JSON.parse(state);
        } catch (err) {
            return undefined;
        }
    };
    
    export const saveState = (state) => {
        try {
            const st = JSON.stringify(state);
            localStorage.setItem('state', st);
        } catch (err) {
    
        }
    };
    
    const throttle = (func, limit) => {
        let lastFunc;
        let lastRan;
        return function() {
            const context = this;
            const args = arguments;
            if (!lastRan) {
                func.apply(context, args);
                lastRan = Date.now();
            } else {
                clearTimeout(lastFunc);
                lastFunc = setTimeout(function() {
                    if ((Date.now() - lastRan) >= limit) {
                        func.apply(context, args);
                        lastRan = Date.now()
                    }
                }, limit - (Date.now() - lastRan))
            }
        }
    };
    
    const store = createStore(AppReducer, loadState());
    
    store.subscribe(throttle(() => {
        // This callback is called on every state change.
        // Here your current state is written to the localStorage
        saveState(store.getState()); 
    }, 2000));
    
    export default store;
    

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 2017-11-28
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      相关资源
      最近更新 更多