代码之家  ›  专栏  ›  技术社区  ›  Julian

防止减速器属性嵌套在状态中

  •  0
  • Julian  · 技术社区  · 8 年前

    我希望组件具有一个名为 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;
    

    Reducer:

    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 回复  |  直到 8 年前
        1
  •  1
  •   Kamalakannan J    8 年前

    基本上,你想要的改变应该发生在减速器上。您正在使用对象作为状态,并在对象内设置等待属性。如果只需要该布尔值,请使用该布尔值作为状态对象,如下所示。

    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;
      }
    }
    

    试试这个,让我知道这个对你是否有效。我关心的一个问题是,它不会更新props,因为它的布尔值是基元类型,而值是存储的,而不是引用。

    最简单的改变是@samvk答案

        2
  •  1
  •   SamVK    8 年前

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

    let mapStateToProps = state => ({
        waiting: state.waiting.waiting
    })
    

    这将使每一个减速器作为一个对象,但至少不会给你在道具本身尴尬的重复性。