在 React 应用程序中使用来自 window 的 Redux 默认存储

Using Redux default store from window in React app

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

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。我怎样才能做到这一点?

显然您正在尝试将状态保存到 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;