防止reducer属性嵌套在状态

时间:2018-07-25 02:16:51

标签: javascript reactjs react-redux

我希望我的组件具有一个名为waiting的布尔属性。我通过setWaiting操作创建者触发了对此属性的更改。唯一的问题是,在我的组件中,此属性嵌套在同名属性中:

在我的组件中,我希望能够做到:

{this.props.waiting}

...但是现在我要做的是:

{this.props.waiting.waiting}

动作创建者:

export const WAITING = "waiting";

export function setWaiting(isWaiting) {
  return {
    type: WAITING,
    payload: isWaiting
  };
}

在我的组件中,我将此操作称为:

this.props.setWaiting(true); // or false depending the case

减速器设置:

import { combineReducers } from "redux";
import { reducer as formReducer } from "redux-form";
import waitingReducer from "./reducer-waiting"

const rootReducer = combineReducers({
    form: formReducer,
    waiting: waitingReducer
});

export default rootReducer;

减速器:

import _ from "lodash";
import { WAITING } from "../actions";

export default function waitinReducer(state = {}, action) {
  if (_.isUndefined(state.waiting)) {
    return Object.assign({}, state, { waiting: false });
  }

  switch (action.type) {
    case WAITING:
      // This is irrelevant here because the problem happens before this
      // ever gets called. Just left it here for completeness sake.
      return Object.assign({}, state, { waiting: action.payload });
    default:
      return state;
  }
}

将状态映射到道具(已经带有“坏”状态):

let mapStateToProps = state => {
  // This prints { waiting: { waiting: false } }
  // but I just want { waiting: false }
  console.log(state) 

  return {
    waiting: state.waiting
  }
}

一些额外的上下文:

react: 16.4.1
react-dom: 16.4.1
redux: 3.7.2
react-redux: 4.4.9

2 个答案:

答案 0 :(得分:1)

您可以尝试仅映射该状态:

test_m

这将使每个reducer成为对象,但至少不会给您道具本身带来的尴尬重复性。

答案 1 :(得分:1)

基本上,所需的更改应在减速器中进行。您正在使用对象作为状态并在对象内部设置waiting属性。如果只需要该布尔值,则将该布尔值用作状态对象,如下所示。

export default function waitinReducer(state = false, action) {
  // default initialisation is false
  // if (_.isUndefined(state.waiting)) {
  //  return Object.assign({}, state, { waiting: false });
  // }

  switch (action.type) {
    case WAITING:
      // just return the payload
      return action.payload;
    default:
      return state;
  }
}

尝试一下,让我知道这是否适合您。我关心的一个问题是,它不会更新道具,因为它的布尔值是原始类型,并且值存储的不是引用。

最简单的更改是@SamVK答案