Javascript 使用多个还原程序和操作时出现问题

Javascript 使用多个还原程序和操作时出现问题,javascript,reactjs,redux,Javascript,Reactjs,Redux,我有个小问题。 我在使用联合减速器的不同文件中有不同的减速器,但是当我尝试使用“不同”时 在这些减速器上的初始状态是不存在的 比如说 产品减速器->这是我必须采取的状态 const INITIAL_STATE = { productosInventario: [], loading: false, error: '' 类别减速器->这是这些减速器的状态 const INITIAL_STATE = { categorias: [], categoriaA

我有个小问题。 我在使用联合减速器的不同文件中有不同的减速器,但是当我尝试使用“不同”时 在这些减速器上的初始状态是不存在的

比如说

产品减速器->这是我必须采取的状态

const INITIAL_STATE = {
    productosInventario: [],
    loading: false,
    error: ''

类别减速器->这是这些减速器的状态

const INITIAL_STATE = {
    categorias: [],
    categoriaActual: '',
    loading: false,
    error: ''
}

其理念是在这些组件上同时使用:

组成部分:


import React, { Component } from 'react'
/* Components */
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import CardItemInventario from '../components/inventario/CardItemInventario'
import * as ProductoActions from '../actions/ProductoActions'
import * as CategoriasActions from '../actions/CategoriasActions'
/* Styles */
import Spinner from '../components/Spinner'
import Fatal from '../components/Fatal'
import '../assets/styles/Containers/Inventario.scss'

class Inventario extends Component {

    async componentDidMount() {
        await this.props.traerTodosLosProductos();
    }

    handleChangeCategoria = (e) => {
        this.props.cambioCategoriaInventario(e.target.value)
        this.props.traerProductosPorCategoriaInventario(e.target.value)
    }

    /* Mapea todas las categorias disponibles en base de datos */
    traerCategoriasInventario = () => this.props.categoriasInventario.map(category => {
        let categori = category.categoria
        return (
            <option
                value={categori}
            >
                {categori}
            </option>
        )
    })


    ponerContenido = () => {
        if (this.props.loading) {
            return (
                <Spinner />
            )
        }
        if (this.props.error) {
            return (
                <Fatal
                    error={this.props.error} />
            )
        }
        return (
            <>
                <div className="button-add__cont">
                    <h1 className="button-add__title">
                        Inventario
                    </h1>
                    <Link to='/agregarinventario' className="button-add__cont--link">
                        Agregar a Inventario
                    </Link>
                </div>
                <select
                    name="categoriaSelect"
                    id=""
                    onChange={this.handleChangeCategoria}
                    className="selector-categoria"
                >
                    <option value='' defaultValue> - Categoria -</option>
                    {this.traerCategoriasInventario()}
                </select>
                <div className="inventario-cont">
                    
                    {this.imprimirProductos()}
                </div>
            </>
        )
    }

    imprimirProductos = () => this.props.productosInventario.map(Productos =>
        <CardItemInventario
            nombre={Productos.nombre}
            marca={Productos.marca}
            cantidad={Productos.cantidad}
            distribuidor={Productos.distribuidor}
            precio={Productos.precio}
        />
    )



    render() {
        console.log(this.props)
        return (
            <>
                {this.ponerContenido()}
            </>
        )
    }
}

const mapStateToProps = (reducers) => {
    return (
        reducers.ProductoReducer,
        reducers.CategoriasReducer
    )
}

const mapDispatchToProps = {
    ...ProductoActions,
    ...CategoriasActions
}

export default connect(mapStateToProps, mapDispatchToProps)(Inventario);
分类作用>

import axios from 'axios'

import { host_name, port_redux } from '../../../config'
import { CARGANDO, ERROR } from '../types/GlobalTypes'
import {
    LISTAR_CATEGORIAS,
    CATEGORIA_ACTUAL
} from '../types/CategoriasTypes'

const axiosConf = {
    baseURL: `http://${host_name}:${port_redux}`
}

export const traerCategoriasInventario = () => (dispatch) => {
    const res = axios.get(`/api/categorias/get/listar`, axiosConf)
    console.log(res)
    dispatch({
        type: LISTAR_CATEGORIAS,
        payload: res.data.data
    })

}

export const cambioCategoriaInventario = (categoria) => async (dispatch) => {
    try {
        dispatch({
            type: CATEGORIA_ACTUAL,
            payload: categoria
        })
    } catch (error) {
        console.log("Error: " + error)
        dispatch({
            type: ERROR,
            payload: error.message
        })
    }
}
看起来你在州和州之间有些混淆。状态是包含所有数据的对象。它只是一个普通的javascript对象。reducer是一个函数,它接受state对象和一个action并返回一个新的state对象

您的设置应如下所示:

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,
})
这里我们有两个单独的还原器,分别用于类别和产品,每个还原器都有一个单独的初始状态。我们使用
combinereducer
将它们组合在一起,因此现在组合状态具有属性
producto
categorias

您的组件
Inventario
需要从以下状态访问一组值:
categoriasiinventario
productionsinventario
加载
,以及
错误
。我们使用
mapstatetops
提取这些值并将其作为道具传递,而不是将状态传递到组件中

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,
    }
}
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,
})
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,
    }
}