想要在reactjs中从同一个reducer返回不同的值

时间:2017-08-08 05:51:55

标签: reactjs

import {FETCH_OBSERVATION} from '../actions/index';
import {DELETE_OBSERVATION} from '../actions/index';

export default function(state={all:[],count:null},action){
  switch (action.type) {
    case FETCH_OBSERVATION:
    console.log("data for fetch observationCount",action.payload.data.model.observationInstanceList);

     return{
       all:state.all.concat(action.payload.data.model.observationInstanceList),
       count:action.payload.data.model.observationCount
     }
    case DELETE_OBSERVATION:
    return state.all=[];
    default:
    return state

  }
  return state;
}

我使用action creator define in action / index file从API获取数据。 任何人都告诉我为什么没有定义state.all.concat?

错误看起来像这样

Cannot read property 'concat' of undefined
at ./src/reducers/reducer_observation.js.__webpack_exports__.a (reducer_observation.js:10)
at combination (combineReducers.js:120)
at dispatch (createStore.js:165)
at redux-logger.js:1
at index.js:28
at dispatch (applyMiddleware.js:35)
at action.payload.then._extends.payload (index.js:25)
at <anonymous>

My Combine Reducer看起来像这样

import { combineReducers } from 'redux';
import SpeciesChartReducer from './reducer_chart_data';
import ObservationReducer from './reducer_observation';
import TaxonReducer from './reducer_taxon_list';
import  UserGroupNames from './reducer_fetch_userGroup';
import  UserGroupObservations from './reducer_fetch_groupobservations';
import  HomeTotalCount from './reducer_home_total_count';

const rootReducer = combineReducers({
  Observation:ObservationReducer,
  ChartData:SpeciesChartReducer,
  treeData:TaxonReducer,
  UserGroupNames:UserGroupNames,
  UserGroupObservations:UserGroupObservations,
  HomeTotalCount:HomeTotalCount
});

export default rootReducer;

1 个答案:

答案 0 :(得分:0)

好的,所以如果你想要上面的功能,那就这样做。

import {FETCH_OBSERVATION} from '../actions/index';
import {DELETE_OBSERVATION} from '../actions/index';
const DEFAULT_STATE={all:[],count:null}
export default function(state=DEFAULT_STATE,action){
  switch (action.type) {
    case FETCH_OBSERVATION:
     return{
       all:state.all.concat(action.payload.data.model.observationInstanceList),
       count:action.payload.data.model.observationCount
     }
    case DELETE_OBSERVATION:
    return DEFAULT_STATE;
    default:
    return DEFAULT_STATE

  }
  return DEFAULT_STATE;
}

`