How to change my state in my reducer, trying to se

2020-05-06 08:37发布

问题:

My reducers are split, and in one of them my initial state and reducer looks like:

import Constants from '../constants';

const initialState = {
  fetching: true,
};

const boards = (state = initialState, action) => {
  switch (action.type) {
    case Constants.BOARDS_FETCHING:
      return state;
    default:
      return state;
  }
};

export default boards;

How can I change the fetching property to true in the BOARDS_FETCHING case?

Update

My .babelrc looks like:

{
  "presets": ["react", "es2015"],
  "env": {
    "development": {
      "presets": ["react-hmre"]
    }
  }
}

Error:

回答1:

You need to install transform-object-rest-spread

 "plugins": ["transform-object-rest-spread"]

For more, please check babeljs-plugins#transform-object-rest-spread



回答2:

You should set it in the case Constants.BOARDS_FETCHING clause:

import Constants from '../constants';

const initialState = {
  fetching: true,
};

const boards = (state = initialState, action) => {
  switch (action.type) {
    case Constants.BOARDS_FETCHING:
      return {...state, fetching: true};
    default:
      return state;
  }
};

export default boards;


回答3:

Replace this:

const boards = (state = initialState, action) => {
  switch (action.type) {
    case Constants.BOARDS_FETCHING:
      return state;
    default:
      return state;
  }
};

to:

const boards = (state = initialState, action) => {
  switch (action.type) {
    case Constants.BOARDS_FETCHING:
      return Object.assign({},state,action.fetching);
    default:
      return state;
  }
};