繁体   English   中英

使用不可变JS映射时如何设置多个对象值

[英]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

有多种方法可以做到这一点

  1. 您可以使用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); 

但是,当您进行多项更改时,这是不可行的

  1. 另一个选项是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.

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