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;

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";
import "../node_modules/font-awesome/css/font-awesome.min.css";

const store = createStore(reducer);

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

ShopHome.js, когда я открываю страницу, появляется TypeError: Невозможно прочитать свойство 'items' undefined, я думаю, что-то не так с mapStateToProps и не могу определить состояние. Интересно, если я сделал что-то не так в редукторе

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 {
  handleClick = id => {
    this.props.addToCart(id);
  };
  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 to="/" onClick={() => this.handleClick(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

когда я добавляю функцию добавления количества, все работает нормально, но после добавления функции вычитания количества оказывается, что состояние не определено (

TypeError: Cannot read property 'items' of undefined
Function.mapStateToProps [as mapToProps]
src/shopHome.js:47
  44 | }
  45 | const mapStateToProps = state => {
  46 |   return {
> 47 |     items: state.items
  48 |   };
  49 | };
  50 | )

ShopCart.js

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

class ShopCart extends Component {
  handleAddQuantity = id => {
    this.props.addQuantity(id);
  };

  handleSubtractQuantity = id => {
    this.props.subtractQuantity(id);
  };
  render() {
    let addedItems = this.props.items.map(item => {
      return (
        <tr key={item.id}>
          <td>{item.name}</td>
          <td>
            <NavLink to="/myCart">
              <span>
                <i
                  className="fas fa-plus-circle"
                  onClick={() => {
                    this.handleAddQuantity(item.id);
                  }}
                ></i>
              </span>
            </NavLink>
            {item.quantity}
            <NavLink to="/myCart">
              <span>
                <i
                  className="fas fa-minus-circle"
                  onClick={() => {
                    this.handleSubtractQuantity(item.id);
                  }}
                ></i>
              </span>
            </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)),
    subtractQuantity: id => dispatch(subtractQuantity(id))
  };
};

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

reducer.js

import { ADD_TO_CART, ADD_QUANTITY, SUBTRACT_QUANTITY } from "./action.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.find(item => item.id === action.id);
    if (existed_item) {
      addedItem.quantity += 1;
      return {
        ...state
      };
    } else {
      addedItem.quantity = 1;
      return {
        ...state,
        addedItems: [...state.addedItems, addedItem]
      };
    }
  }

  if (action.type === ADD_QUANTITY) {
    let addedItem = state.items.find(item => item.id === action.id);
    addedItem.quantity += 1;
    return {
      ...state
    };
  }

  if (action.type === SUBTRACT_QUANTITY) {
    let addedItem = state.items.find(item => item.id === action.id);
    if (addedItem.quantity === 1) {
      let newItem = state.addedItems.filter(item => item.id !== action.id);
      return {
        ...state,
        addedItems: newItem
      };
    } else {
      addedItem.quantity -= 1;
      return {
        ...state
      };
    }
  }
};

export default reducer;

action_type.js

import { ADD_TO_CART, ADD_QUANTITY, SUBTRACT_QUANTITY } from "./action";

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

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

export const subtractQuantity = id => {
  return {
    type: SUBTRACT_QUANTITY,
    id
  };
};

action.js

export const ADD_TO_CART = "ADD_TO_CART";

export const ADD_QUANTITY = "ADD_QUANTITY";

export const SUBTRACT_QUANTITY = "SUBTRACT_QUANTITY";

Привет всем, я новичок в реагировать на избыточность, когда я открываю страницу, страница постоянно говорит мне, что TypeError: Невозможно прочитать свойства 'items' undefined в ShopHome.js, я предполагаю, что что-то не так с объявлением состояния в Функция mapStateToProps. кто-нибудь может мне помочь?

0
Zhunan Shuai 21 Дек 2019 в 04:38

1 ответ

Я думаю, в вашем reducer.js По умолчанию вы должны return initialState;

0
Tai Le 21 Дек 2019 в 07:22