[英]immutablejs (react/redux) , “push” into state with immutable
[英]React Redux: Using Immutable in Reduce State
我正在學習Immutable.js,但在簡化器中難以處理Immutable.js。
我已經這樣聲明了我的initialState:
import { fromJS } from 'immutable';
const INITIAL_STATE = fromJS({
users: {
isLoading: false,
items: []
}
});
我正在嘗試修改initialState,但出現錯誤:“ state.setIn不是函數”。
case 'FETCH_USERS_SUCCESS':
return state
.setIn(['users', 'isLoading'], false)
.setIn(['users', 'items'], action.users)
在index.js中,我將默認狀態聲明為Immutable Map()對象:
let store = createStore(..., Map({}), composeEnhancers(...));
在combinedReducers中,我使用的是“ redux-immutable”。
import { combineReducers } from 'redux-immutable';
用Immutable.js修改減速器狀態的正確方法是什么?
toJS和fromJS是昂貴的操作。 您不應該執行initial_state或state的fromJS。
我建議您在用戶減速器上執行此操作,以獲得更好的性能,並且不要使用toJS和fromJS。 並在代碼(選擇器,組件,視圖)中使用get來檢索任何值。
import { List as ImmutableList, Map as ImmutableMap } from 'immutable'; import { FETCH_USERS_SUCCESS } from './constants'; // or whatever you have your constants file const initialState = new ImmutableMap({ isLoading: false, items: new ImmutableList([]); }); function users(state = initialState, action) { switch (action.type): case FETCH_USERS_SUCCESS: return state.merge({ isFetching: false, users: action.users }); default: return state; }
請在創建商店時不要使用不可變的。 您不需要執行任何不可變的操作,因為它認為商店是不可變的。 因此,Reducer內部的任何數據結構都應為不可變的。
這是一個常見的配置存儲文件(或您的情況下的索引)的示例:
import { applyMiddleware, createStore } from 'redux'; import { composeWithDevTools } from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import rootReducer from 'state/reducers'; export default function configureStore(initialState = {}) { const store = createStore( rootReducer, initialState, composeWithDevTools(applyMiddleware(thunk)), ); // to query state in the console window.appState = store.getState(); if (module.hot) { const nextReducer = require('state/reducers'); module.hot.accept('state/reducers', () => { store.replaceReducer(nextReducer); }); } return store; }
在文件狀態/化簡器中,您具有所有不同實體的化簡器:
import { combineReducers } from 'redux'; import users from './users'; const ownReducers = {}; const appReducer = combineReducers({ ...ownReducers, // add here your reducers after importing the entity state // ie: myStuff: myStuff.reducer, etc... users: claims.reducer, }); const rootReducer = (state, action) => { return appReducer(state, action); }; export default rootReducer;
最好!
我假設在reducer中返回的state
不是一個不變的映射。 據我所知,您只是通過使用fromJS(...)
將初始狀態轉換為不可變的映射,您可以嘗試在化fromJS(...)
中執行相同的操作。
return fromJS(state)
.setIn(.setIn(['users', 'isLoading'], false)
.setIn(['users', 'items'], fromJS(action.users))
但我建議您看一下本文檔 ,因為它可以滿足您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.