为了账号安全,请及时绑定邮箱和手机立即绑定

使用多个 Reducer 和 Actions Redux 的问题

使用多个 Reducer 和 Actions Redux 的问题

ABOUTYOU 2023-05-25 16:23:42
我有一个小问题。我在不同的文件中使用组合减速器有不同的减速器,但是当我尝试在这些减速器上使用“不同的”初始状态时,它没有出现例如Product Reducer -> 这是我必须采取的状态const INITIAL_STATE = {    productosInventario: [],    loading: false,    error: ''Category Reducer -> 这是这些减速器的状态const INITIAL_STATE = {    categorias: [],    categoriaActual: '',    loading: false,    error: ''}这个想法是在这些组件上同时使用:
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

const mapStateToProps = (reducers) => {

    return (

        reducers.ProductoReducer,

        reducers.CategoriasReducer

    )

}

看起来你在状态和减速器之间有一些混淆。状态是包含所有数据的对象。它只是一个普通的 javascript 对象。reducer 是一个函数,它接受状态对象和一个动作并返回一个新的状态对象。


您的设置应如下所示:


const productoReducer = (state = INITIAL_PRODUCTOS, action ) => {

  switch ( action.type ) {

    case 'TRAER_TODOS_LOS_PRODUCTOS':

      /* ... code here ... */

    default:

      return state;

  }

}


const categoriasReducer = (state = INITIAL_CATEGORIAS, action ) => {

  switch ( action.type ) {

    case 'LISTAR_CATEGORIAS':

      /* ... code here ... */

    default:

      return state;

  }

}


export const reducer = combineReducers({

  producto: productoReducer,

  categorias: categoriasReducer,

})

这里我们有两个单独的类别和产品缩减器,每个都有一个单独的初始状态。我们过去常常combineReducers将它们放在一起,所以现在组合状态具有属性producto和categorias。


您的组件Inventario需要从状态访问一堆值: categoriasInventario, productosInventario, loading, 和error。我们没有将状态传递到组件中,而是使用mapStateToProps提取这些值并将它们作为道具传递。


const mapStateToProps = (state) => {

    return {

        categoriasInventario: state.categorias.categorias,

        productosInventario: state.productos.productosInventario,

        loading: state.categorias.loading || state.productos.loading,

        error: state.categorias.error || state.productos.error,

    }

}


查看完整回答
反对 回复 2023-05-25
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信