![](/img/trans.png)
[英]Js immutable - how to flatten a map to a Set<number>
[英]How to set multiple object values when using Immutable JS map
我是redux的新手,請在以下代碼中執行redux的這種正確方法嗎? 當調用操作執行currentTime時,這是一個reducer方法。
import { combineReducers } from 'redux';
import { UPDATE_TIME } from './actions';
import { Map } from 'immutable';
const initialState = Map({update:false, currentTime: ""});
function currentTime(state = initialState, action) {
switch (action.type) {
case UPDATE_TIME:
return {...state, update: true, currentTime: action.time };
default:
return state;
}
}
const currentTimeReducer = combineReducers({
currentTime
});
export default currentTimeReducer
有多種方法可以做到這一點
您可以使用set()
函數設置值
case UPDATE_TIME: state = state.set('update', true); return state.set('currentTime', action.time);
甚至
case UPDATE_TIME: return state.set('update', true) .set('currentTime', action.time);
但是,當您進行多項更改時,這是不可行的
另一個選項是merge()
case UPDATE_TIME: return state.merge({update: true, currentTime: action.time})
但是,在嵌套狀態更新的情況下,您需要執行deepMerge。 查看mergeDeep
的詳細信息
我們使用不可變的JS在現有對象中的每個小變化上創建新實例。 不可變的JS MAP有一個set
方法來設置屬性並返回對象的新實例。 在這里您可以找到MAP的api文檔
import { combineReducers } from 'redux';
import { UPDATE_TIME } from './actions';
import { Map } from 'immutable';
const initialState = Map({update:false, currentTime: ""});
function currentTime(state = initialState, action) {
switch (action.type) {
case UPDATE_TIME:
let newState = state;
newState = newState.set('update', true );
newState = newState.set('currentTime', action.time);
return newState;
default:
return state;
}
}
const currentTimeReducer = combineReducers({
currentTime
});
export default currentTimeReducer
在此文檔中查看最佳做法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.