【问题标题】:How to update reducer with right state?如何以正确的状态更新减速器?
【发布时间】:2018-06-17 05:35:23
【问题描述】:

在我的 react/redux 应用程序中,我有这个减速器:

import {fromJS} from 'immutable';

import {
  CHANGE_USERNAME,
  ADD_COUNTER
} from './constants';

// The initial state of the App
const initialState = fromJS({
  username: '',
  counter:0
});

function homeReducer(state = initialState, action) {
  switch (action.type) {
    case CHANGE_USERNAME:
      // Delete prefixed '@' from the github username
      return state
        .set('username', action.name.replace(/@/gi, ''));
    case ADD_COUNTER:
      return state
        .set('counter',state.counter+1)
    default:
      return state;
  }
}

export default homeReducer;

目前它命中了减速器,但没有更新计数器的状态。我错过了什么?链接到code

【问题讨论】:

    标签: reactjs redux react-boilerplate


    【解决方案1】:

    你使用 immutable.js 所以你必须使用 get 来读取值

    return state.set(‘counter’, state.get(‘counter’) + 1)
    

    您的代码也在导入fromJS,但没有使用它。

    Immutable.js 有一个非常非 JavaScripty 的语法,如果你不习惯它并且真的想在 Redux 中使用不变性,我建议你考虑使用 Mori-Redux 或无缝不可变,这两者都可以让你正确的js语法。

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2019-07-05
      • 2017-11-10
      • 1970-01-01
      • 2018-06-06
      相关资源
      最近更新 更多