Состояние моего реактора-редуктора не обновляется - PullRequest
0 голосов
/ 04 июня 2018

Мой редуктор не обновляет состояние. Мои действия отправляются, но мой редуктор не обновляет мое состояние. У моего состояния приложения есть два объекта product (Array) и cart (array).

У моего приложения естьдва редуктора

  1. cartReducer

export  function cartReducer(state={cart:[
{id:1},
{id:2}
]},actions){
        switch(actions.payload)
        {
            case "ADD_TO_CART":
            console.log("Reducer called")
            return {cart:[...state.cart,...actions.payload]}
            default:
            return state;
        }
    }
productReducer

export  function ProductReducer(state={
product:[{
    id:1,
    ProductName:"LG TV",
    Description:"This is the best tv available today in the market.This is the best tv available today in the market.This is the best tv available today in the market.This is the best tv available today in the market",
    Price:200,

    },
    {
        id:2,
        ProductName:"Apple TV",
        Description:"This is the best tv available today in the market",
  
        Price:300,
    },
    {
        id:3,
        ProductName:"Hp TV",
        Description:"This is the best tv available today in the market",
  
        Price:400,
    },{
        id:5,
        ProductName:"LC TV",
        Description:"This is the best tv available today in the market",
        Price:700,
    }]},actions){
    switch(actions.payload)
    {
        case "ADD_PRODUCT":
        return {product:[...state.product,...actions.payload]}
        default:
        return state;
    }
}
Мой комбайнредуктор (index.js)

import {combineReducers} from 'redux';
import {ProductReducer} from './ProductReducer.js';
import {cartReducer} from './cartReducer.js';

const rootReducer=combineReducers({
    product:ProductReducer,
    cart:cartReducer
})

export default rootReducer

Мои файлы действий:

  1. cartActions

export function addToCart(data) 
 {
     console.log("Actions called")
     return {
         type:"ADD_TO_CART",
          payload: data
     } 
 };

Мой основной файл index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import '../node_modules/materialize-css/dist/css/materialize.min.css';
import '../node_modules/materialize-css/dist/js/materialize.min.js';
import reducers from './reducers/index';
const store=createStore(reducers);

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root'));

Я могу получить доступ к начальному состоянию из редукторов, используя mapStateToProps в моих компонентах ProductDescription.js и ProductList.js

  1. ProductList.js

import React, { Component } from 'react';
import {connect} from 'react-redux';
import ProductDescription from './ProductDescription';
class ProductList extends Component {
     componentDidMount(){
     }
  render() {
      const arr=this.props.product.map((data)=>{
        return(
        <li key={data.id}>
       <ProductDescription data={data} />

          </li>
      )});
 
    return (
      <div className="row">
      <div className="col s12 ">
        <div className="card ">
          <div className="card-content ">
          <h2 >Product List</h2>
          <br/>
          <hr/>
          <br/>
          <ul>
           {arr}
            </ul>
          </div>
      </div>
    </div>
        </div>      
    );
  }
}
function mapStateToProps(state)
{
  return {
    cart:state.cart.cart,
    product:state.product.product,
  }
}

export default connect(mapStateToProps)(ProductList);
ProductDescription.js

import React, { Component } from 'react';
import {connect} from 'react-redux';
import  {addToCart} from '../Actions/cartActions';
import {bindActionCreators} from 'redux';

class ProductDescription extends Component {
handleCart()
  {
    const data1=[...this.props.cart,
      {
        id:this.props.data.id,
        ProductName:this.props.data.ProductName,
        Description:this.props.data.Description,
        Price:this.props.data.Price,
      }];
      console.log(data1);
   this.props.addToCart(data1);
  setTimeout(()=>{console.log(this.props.cart)},3000);
  
  } 
  
  render() {
    return (
      <div className="row">
        <div className="col s12">
        <div className="card">
        <div className="card-content">
          <div className="card-title">
          {this.props.data.ProductName}
          </div>
          <hr/>
          <div>
          {this.props.data.Description}
          </div>
          <hr/>
          <div >
          Price :{this.props.data.Price}
          <br/>
          </div>
          
          <div className="right">
            <button  onClick={this.handleCart.bind(this)} className="waves-effect waves-light btn" >Add To Cart</button>      
            </div>
            <br/>
            <br/>
        </div>
          </div>
          </div>
          </div>
    );
  }
}
function mapStateToProps(state)
{
  return{
  cart:state.cart.cart,
  }
}
function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    addToCart:addToCart  
  },dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(ProductDescription);

Но я не могу получить обновленное состояние корзины из console.log (this.props.cart) в ProductDescription.js.Несмотря на то, что у меня есть тайм-аут на 3000. Я даже поместил оператор console.log в CartReducer.js, чтобы проверить, доступен ли редуктор или нет. Но оператор console.log не вызывается.

Ниже вывод моей консоли:

Выход Console.log

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...