在redux中未调用mapStateToProps,状态未定义

时间:2019-12-21 01:38:16

标签: javascript reactjs react-redux

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”,我猜它与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";

大家好,我是React-redux的新手,当我打开页面时,页面不断告诉我TypeError:无法读取ShopHome.js中未定义的属性“ items”,我认为声明mapStateToProps函数中的状态。有人可以帮我吗?

0 个答案:

没有答案