简体   繁体   中英

why my shopping cart not re-render after the change the state of the product

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import "bootstrap/dist/css/bootstrap.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./reducer";

const store = createStore(reducer);

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

App.js

import React, { Component } from "react";
import "./App.css";
import Router from "./Router";

class App extends Component {
  render() {
    return (
      <div className="App">
        <div>
          <h1>React-Redux Store</h1>
          <h2>Welcome to the React Store</h2>
        </div>
        <Router />
      </div>
    );
  }
}

export default App;

ShopHome.js

import React, { Component } from "react";
import { NavLink } from "react-router-dom";
import { connect } from "react-redux";
import { addToCart } from "./action_type";

class ShopHome extends Component {
  render() {
    return (
      <div>
        <table className="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Description</th>
              <th>Price</th>
              <th>
                <NavLink to="/myCart" exact activeStyle={{ color: "green" }}>
                  <a href="#">my cart</a>
                </NavLink>
              </th>
            </tr>
          </thead>
          <tbody>
            {this.props.items.map(item => {
              return (
                <tr key={item.id}>
                  <td>{item.name}</td>
                  <td>{item.description}</td>
                  <td>${item.price}</td>
                  <button onClick={this.props.addToCart(item.id)}>
                    add to cart
                  </button>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}
const mapStateToProps = state => {
  return {
    items: state.items
  };
};

const mapDispatchToProps = dispatch => {
  return {
    addToCart: id => {
      dispatch(addToCart(id));
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ShopHome);

ShopCart.js

import React, { Component } from "react";
import { NavLink } from "react-router-dom";
import { connect } from "react-redux";
import { addQuantity } from "./action_type";

class ShopCart extends Component {
  render() {
    let addedItems = this.props.items.map(item => {
      return (
        <tr key={item.id}>
          <td>{item.name}</td>
          <td>
            <NavLink to="/myCart">
              <i
                class="glyphicon glyphicon-plus-sign"
                onClick={this.props.addQuantity(item.id)}
              ></i>
              {item.quantity}
              <i
                class="glyphicon glyphicon-minus-sign"
                onClick={this.props.handleSubtractQuantity(item.id)}
              ></i>
            </NavLink>
          </td>
          <td>${item.price}</td>
        </tr>
      );
    });
    return (
      <div>
        <table className="table">
          <thead>
            <tr>
              <th>Item</th>
              <th>Quantity</th>
              <th>Price</th>
              <th>
                <NavLink to="/" exact activeStyle={{ color: "green" }}>
                  <a href="#">back to store</a>
                </NavLink>
              </th>
            </tr>
          </thead>
          <tbody>{addedItems}</tbody>
        </table>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    items: state.addedItems
  };
};

const mapDispatchToProps = dispatch => {
  return { addQuantity: id => dispatch(addQuantity(id)) };
};

export default connect(mapStateToProps, mapDispatchToProps)(ShopCart);

reducer.js

const initialState = {
  items: [
    {
      id: 1,
      name: "apple",
      description: "Eat One Every Day, may keep the doctor away",
      price: 12
    },
    {
      id: 2,
      name: "grape",
      description: "Wine is great, but grapes is better",
      price: 11
    },
    {
      id: 3,
      name: "pineapple",
      description: "enjoy but don`t forget to peer first",
      price: 8
    }
  ],
  addedItems: []
};

const reducer = (state = initialState, action) => {
  if (action.type === "ADD_TO_CART") {
    let addedItem = state.items.find(item => item.id === action.id);
    let existed_item = state.addedItems;
    if (existed_item) {
      addedItem.quantity++;
    } else {
      addedItem.quantity = 1;
    }
    return {
      ...state,
      addItems: [...state.addedItems, addedItem]
    };
  }
  if (action.type === "ADD_QUANTITY") {
    let addedItem = state.items.find(item => item.id === action.id);
    addedItem.quantity++;
  }
  return {
    ...state
  };
};

export default reducer;

action_type.js

export const addToCart = id => {
  return {
    type: "ADD_TO_CART",
    id
  };
};

export const addQuantity = id => {
  return {
    type: "ADD_QUANTITY",
    id
  };
};

Router.js

import React from "react";
import { Switch, Route } from "react-router-dom";
import ShopHome from "./shopHome";
import ShopCart from "./shopCart";
import { BrowserRouter } from "react-router-dom";

const Router = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={ShopHome} />
        <Route exact path="/myCart" component={ShopCart} />
      </Switch>
    </BrowserRouter>
  );
};

export default Router;

Hi everyone, I am new to react-redux, I am trying to setting up a shopping cart website, I have a main shopping cart page which host on localhost:3000, and once i pressed the my cart, will be route to /myCart, however, my problem is when i select the item and add to cart, and newest added item in the ShopCart component won't be rendered in my cart, I am not sure where i did wrong, can someone give me a hand?

I supposed ideally when i clicked the add to cart in the ShopHome.js, will trigger the addToCart function, then through the dispatcher, with action.type= "ADD_TO_CART" and id=item.id, then in the reducer, i want the quantity of selected item plus 1,However, when i pressed add to cart, and hit my cart, nothing is added.

First, you have a typo in your reducer.

addItems: [...state.addedItems, addedItem] It should be addedItems: [...state.addedItems, addedItem]

Next, you should rewrite the logic for ADD_TO_CART .

 let existed_item = state.addedItems;
    if (existed_item) {
      addedItem.quantity++;
    } else {
      addedItem.quantity = 1;
    }

You assigning existed_item to state.addedItems which is an array, so existed_item will always be true and it will try to increment a property that does exist.

Instead, change existed_item = state.addedItems to existed_item = state.addedItems.find(x=>x.id === action.id) . If this item exists, increment, otherwise, add quantity = 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM