简体   繁体   English

如何访问 redux state 的初始值?

[英]How to access the initial values of the redux state?

I have a problem and I hope you can help me.我有一个问题,希望你能帮助我。 I did a implementation of redux and using local storage I managed to keep the data when reloading the page.我实现了 redux 并使用本地存储在重新加载页面时设法保留了数据。 I can see them from the redux extension.我可以从 redux 扩展中看到它们。

Why the state after reloading the page is in a different format?为什么重新加载页面后的 state 格式不同? initially is a JavaScript object, after reloading a Map object最初是 JavaScript object,在重新加载 Map ZA8CFDE6331BD59EB2AC96F8911C4B6 后

The problem is that accessing those properties after the page has been reloaded is lost or rather, they come in a different way.问题是在页面重新加载后访问这些属性会丢失,或者更确切地说,它们以不同的方式出现。 For clarity, this is how you see the properties without reloading the page by making a console.log from the component:为清楚起见,这是您在不重新加载页面的情况下通过从组件创建console.log来查看属性的方式:

consolelog component before之前的控制台日志组件

and this is how looks the console.log after reloading the page, the properties are contained in another property called nodes这就是重新加载页面后console.log的外观,属性包含在另一个名为nodes的属性中

consolelog component after之后的控制台日志组件

My state looks the same both without reloading or reloading the page:我的 state 看起来都一样,无需重新加载或重新加载页面:

store redux商店 redux

The implementation of load and save state is as follows:加载和保存state的实现如下:

import {fromJS} from 'immutable'

export const loadState = () => {
  try {
    const serializedData = localStorage.getItem('state')
    if (serializedData === null){
      return undefined 
    }
    return (JSON.parse(serializedData)) 
  } catch (error) {
    return undefined 
  }
}

export const saveState = (state) => {
  try {
    let serializedData = JSON.stringify(state.toJS())
    localStorage.setItem('state', serializedData)
  } catch (error) {

  }
}

and my configureStore looks like this:我的 configureStore 看起来像这样:

import { createStore, applyMiddleware, compose } from 'redux';

import { fromJS } from 'immutable';
import { routerMiddleware } from 'connected-react-router/immutable';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
import sagas from '../utils/sagas';

import {loadState, saveState} from '../storage/index'
const sagaMiddleware = createSagaMiddleware();


export default function configureStore(initialState ={}, history) {

  const middlewares = [sagaMiddleware, routerMiddleware(history)];

  const enhancers = [applyMiddleware(...middlewares)];
  const initialData = loadState();

  const composeEnhancers = process.env.NODE_ENV !== 'production'
    && typeof window === 'object'
    && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
          shouldHotReload: false,
        })
      : compose;
  /* eslint-enable */
  const store = createStore(

    createReducer(),
    fromJS(initialData),
    composeEnhancers(...enhancers),


  );
  store.subscribe(function(){
    saveState(store.getState())
  })

  // Extensions
  sagaMiddleware.run(sagas);
  store.injectedReducers = {}; // Reducer registry
  store.injectedSagas = {}; // Saga registry

  return store ;
}

Reducers:减速机:

import { reducer as form } from 'redux-form/immutable';

import { combineReducers } from 'redux-immutable';
//import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router/immutable';
import history from 'utils/history';
import * as storage from 'redux-storage';

// Global Reducers
import languageProviderReducer from 'containers/LanguageProvider/reducer';
import authReducer from './modules/authReducer';
import uiReducer from './modules/uiReducer';
import initval from './modules/initFormReducer';
import adminReducer from './modules/adminReducer'

/**
 * Creates the main reducer with the dynamically injected ones
 */
export default function createReducer(injectedReducers = {}) {
  const rootReducer = storage.reducer(combineReducers({
    form,
    ui: uiReducer,
    initval,
    authReducer,
    adminReducer,

    router: connectRouter(history),
    ...injectedReducers,
  }));

  // Wrap the root reducer and return a new root reducer with router state
  const mergeWithRouterState = connectRouter(history);
  return mergeWithRouterState(rootReducer);
}

mapStateToProps in the component:组件中的 mapStateToProps:

const mapStateToProps = state => ({
  state: state.get('authReducer','authReducer')
});

I think it can be the format in which the loadState() is loaded but I don't understand why in the redux extension you see the state exactly the same as without reloading.我认为它可能是加载 loadState() 的格式,但我不明白为什么在 redux 扩展中你看到 state 与不重新加载完全相同。 Any suggestions or how could I correct this?有什么建议或我该如何纠正?

The issue is when you initially load the state in configureStore , you use fromJS .问题是当您最初在configureStore加载 state 时,您使用fromJS By default, POJOs are converted to Map instances.默认情况下,POJO 被转换为Map实例。

You need to decide how you want your data to be stored, if you want an immutable object that feels like a POJO then consider using a Record .您需要决定如何存储您的数据,如果您想要一个感觉像 POJO 的不可变 object,那么请考虑使用Record

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM