【问题标题】:Redux store shape : Not getting the correct redux store/state shapeRedux 存储形状:没有得到正确的 redux 存储/状态形状
【发布时间】:2020-01-15 06:48:04
【问题描述】:

我无法获得正确的 redux 存储/状态形状。

我有 2 个用于图像和视频的 reducer 函数,如下所示 -

imageReducer.js -

const initialState = {
  images:{
    imageArray:[],
    selectedImage:{}
  }
}

export default function (state = initialState,action) {
  switch(action.type) {
    case types.FLICKR_IMAGES_SUCCESS:
      return {
        ...state, 
        images: {
        ...state.images.imageArray,...action.images
      }
    }
    case types.SELECTED_IMAGE:
      return {
        ...state,
        images: {
          ...state.images.selectedImage,...action.image
        }
      }
      default:
        return state;
  }
}

videoReducer.js -

const initialState = {
  videos:{
    videoArray:[],
    selectedVideo:{}
  }
}

export default function (state = initialState,action) {
  switch(action.type) {
    case types.SHUTTER_VIDEOS_SUCCESS:
      return {
        ...state, 
        videos: {
        ...state.videos.videoArray,...action.videos
      }
    }
    case types.SELECTED_VIDEO:
      return {
        ...state,
        images: {
          ...state.videos.selectedVideo,...action.video
        }
      }
       default:
      return state;
  }
}

根减速器 -

import { combineReducers } from 'redux';
import img from './imageReducer';
import vid from './videoReducer';

// Combines all reducers to a single reducer function
const rootReducer = combineReducers({
  img, 
  vid
});

我得到的最终 redux 状态与 initialState 的形状不匹配,我希望我的最终状态形状与传递给减速器函数的 initialState 一样

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您的 reducer 在返回数据时实际上创建了不同的结构。将减速器更改为此应该可以解决问题。

    const initialState = {
      images:{
        imageArray:[],
        selectedImage:{}
      }
    }
    
    export default function (state = initialState,action) {
      switch(action.type) {
        case types.FLICKR_IMAGES_SUCCESS:
          return { 
            images: {
            ...state.images,
            imageArray: [
                ...state.images.imageArray,...action.images
             ]
          }
        }
    case types.SELECTED_IMAGE:
          return {
            images: {
              ...state.images,
              selectedImage: {
                ...state.images.selectedImage, ...action.image
              }
    
            }
          }
          default:
            return state;
       }  
      }
    }
    

    视频缩减器也是如此。另外,我认为最好从状态对象中删除images 和videos 键,这样您就可以调用props.img.imageArray 而不是调用props.img.images.imageArray。

    希望对你有帮助

    【讨论】:

    • 您的代码抛出错误 - 未处理的拒绝 (TypeError): state.imageArray is not iterable
    • @Vishwanath 我的错,应该是...state.images.imageArray。更新了答案。
    • 感谢解决了我的问题,是的,我从状态对象中删除了图像和视频键
    • @Vishwanath 欢迎您。很高兴我能提供帮助。
    猜你喜欢
    • 2019-06-02
    • 2016-04-21
    • 2020-05-13
    • 2020-07-22
    • 2020-01-05
    • 2018-09-26
    • 2022-10-20
    • 2018-01-21
    • 2021-07-22
    相关资源
    最近更新 更多