如何使用React和Redux传递数据?

时间:2019-12-25 22:46:52

标签: reactjs redux react-redux

嗨,我开始学习有关react和redux的更多信息,但是我在通过API调用传递数据时遇到了问题

我尝试使用console.logs和Deve工具进行调试。无法弄清楚为什么我的农产品标签上没有数据。

感谢您的帮助

这是我对产品采取的行动:

import * as types from "./types";

export const receiveProducts = () => async dispatch => {
  const response = await fetch("https://api.myjson.com/bins/m2w5s");
  const data = await response.json();
  dispatch({ type: types.RECEIVED_PRODUCTS_SUCCESSFULLY, payload: data });
};

组件项:

import React from "react";
import { connect } from "react-redux";
import { addProductToCart, updateCart } from "../actions/cartAction";
import "./product.css";

class ProductItem extends React.Component {
  handleOnclick = product => {
    if (this.props.cart.length > 0) {
      let id = product.id;
      let cartIndex = this.props.cart.findIndex(cart => {
        return cart.id === id;
      });
      if (cartIndex === -1) {
        this.props.addProductToCart(product);
      } else {
        this.props.updateCart(id, "+");
      }
    } else {
      this.props.addProductToCart(product);
    }
  };
  render() {
    const { price, description, img } = this.props.product;
    return (
      <div className="card-image">
        <img src={img} alt="products" />
        <span className="card-description">{description}</span>
        <hr />
        <div className="card-content">
          <p>{description}</p>
          <h3>$ {price}</h3>
        </div>
        <button
          onClick={() => {
            this.handleOnclick(this.props.book);
          }}
        >
          Buy
        </button>
      </div>
    );
  }
}
const mapStateToProps = state => {
  return {
    cart: state.cart.cart
  };
};
export default connect(
  mapStateToProps,
  { addProductToCart, updateCart }
)(ProductItem);

组件列表:

import React from "react";
import ProductItem from "./ProductItem";
import { connect } from "react-redux";
import { receiveProducts } from "../actions/productAction";
import "./product.css";

class ProductList extends React.Component {
  componentDidMount() {
    this.props.receiveProducts();
  }
  render() {
    const { products } = this.props;
    const productList = products.map(product => (
      <ProductItem product={product} key={product.id} />
    ));
    return (
      <div>
        <h1>Produce</h1>
        <div className="products-container">{productList}</div>
      </div>
    );
  }
}
const mapstateToProps = state => {
  return {
    products: state.products.products
  };
};
export default connect(
  mapstateToProps,
  { receiveProducts }
)(ProductList);

1 个答案:

答案 0 :(得分:2)

您在文件reducers/index.js中犯了一个错误,您写道:

const rootReducer = combineReducers({
 books: productReducer,
 cart: cartReducer
});

代替

const rootReducer = combineReducers({
 products: productReducer,
 cart: cartReducer
});

这是包含固定版本的sandbox