在多个reducer redux中响应单个Redux操作

时间:2018-11-13 10:10:41

标签: reactjs redux

我在项目中使用了多个reducer,然后将它们与CombineReducers()函数结合使用,并且所有操作都在一个文件中。当我分派动作时,它会将状态值返回未定义。我认为由于多个reducerse而无法找到它。但是当我使用单个reducer文件时。一切正常。谁能告诉我问题所在。这就是我如何组合减速器。

const rootReducer = combineReducers({
  isMobileReducer,
  imageSliderReducer
})

,然后传递到存储,如下所示:

let store = createStore(rootReducer,applyMiddleware(thunk))

在前端,我如何访问状态

const mapStateToProps = (state) => ({
 images: state.images,
 isMobile: state && state.isMobile
})

imageSliderReducer.js

import {
 FETCH_IMAGES_BEGIN,
 FETCH_IMAGES_SUCCESS,
 FETCH_IMAGES_FAILURE
} from '../actions/actionTypes'

const initialState = {
 images:[],
 error:null
}

const imageSliderReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_IMAGES_BEGIN:
      return {...state,error:null}
    case FETCH_IMAGES_SUCCESS:
      return {...state,images:action.payload.images}
    case FETCH_IMAGES_FAILURE:
      return {...state,error:action.payload.error,images:[]}
    default:
      return state
  }
}
export default imageSliderReducer;

isMobileReducer.js

import {
 OPEN_MENU,
 CLOSE_MENU,
 SET_DEVICE_TYPE,
} from '../actions/actionTypes'

const initialState = {
 isMenuOpen: null,
 isMobile: false
}

const isMobileReducer = (state = initialState, action) => {
  switch (action.type) {
   case OPEN_MENU:
    return {...state, isMenuOpen: true}
   case CLOSE_MENU:
    return {...state, isMenuOpen: false}
   case SET_DEVICE_TYPE: 
    return {...state, isMobile: action.isMobile}
   default:
    return state
  }
}

export default isMobileReducer;

actionCreator.js

import { 
 OPEN_MENU,
 CLOSE_MENU,
 SET_DEVICE_TYPE,
 FETCH_IMAGES_BEGIN,
 FETCH_IMAGES_SUCCESS,
 FETCH_IMAGES_FAILURE
} from './actionTypes'

export function openMenu(isMobile) {
 return {
  type: OPEN_MENU
 }
}

export function closeMenu(isMobile) {
 return {
  type: CLOSE_MENU
 }
}

export function setDeviceType (isMobile) {
 return {
  type: SET_DEVICE_TYPE,
  isMobile: isMobile
 }
}

 export function fetchImages() {
 return dispatch => {
  dispatch(fetchImagesBegin());
   return fetch("https://7344.rio.com/wp-json/customapi/homeslider")
  .then(handleErrors)
  .then(res => res.json())
  .then(json => {
    dispatch(fetchImagesSuccess(json.posts));
    return json.posts;
  })
  .catch(error => dispatch(fetchImagesFailure(error)));
};
}


function handleErrors(response) {
 if (!response.ok) {
   throw Error(response.statusText);
 }
 return response;
}

export const fetchImagesBegin = () => ({
 type: FETCH_IMAGES_BEGIN
});

export const fetchImagesSuccess = images => ({
 type: FETCH_IMAGES_SUCCESS,
 payload: { images }
});

export const fetchImagesFailure = error => ({
 type: FETCH_IMAGES_FAILURE,
 payload: { error }
});

1 个答案:

答案 0 :(得分:0)

尝试使用此:

    const mapStateToProps = (state) => ({
  images: state.imageSliderReducer.images,
  isMobile: state.isMobileReducer.isMobile
 })