猿问

如何使用 Redux 和 ReactJS 向功能组件添加动作

我尝试将操作“addProduct”添加到组件中。但是当我点击它时看到一个错误,帮助我应对,在此先感谢!


我不明白我的错误在哪里(


import { bindActionCreators } from "redux";

import { addProduct } from "../actions/addProduct";


const ProductListItem = ({ product }) => {

  return (

    <div className="product">

      <img className="product_img" src={product.image} />

      <p>{product.name}</p>

      <p className="bold">$ {product.price}</p>

      <button className="add_card" onClick={() => addProduct(product)}>

        {" "}

        add to cart

      </button>

    </div>

  );

};


export default ({ products = [] }) =>

  products.map((product, i) => {

    return <ProductListItem key={i} product={product} />;

  });



const mapDispatchToProps = dispatch => {

  return bindActionCreators({ addProduct }, dispatch);

};


connect(null,

  mapDispatchToProps

)(ProductListItem);

[enter image description here][1]


MYYA
浏览 108回答 2
2回答

沧海一幻觉

我做了一些更新,并包含了我正在做的事情的一个例子。看起来你需要connect从react-reduxaddProduct既然你已经映射了它,你需要从你的道具中解构mapDispatchToProps我重新定义mapDispatchToProps为不使用bindActionCreators,这只是一个偏好问题,但两者都应该有效。在您的 中connect(),我通过使用...rest&nbsp;并将其传播到返回的道具中来解构所有剩余的道具。..家长import React from "react"import ProductListItem from "./ProductListItem"const products = [1,2,3] <-- data might be in redux-state but I'll use this for simplicity.const TestHolder = () => {&nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ProductListItem products={products}/>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}export default TestHolder产品列表项import React from "react"import { connect } from "react-redux"import { addProduct } from "../../actions/testActions";const ProductListItem = ({ product, addProduct }) => {&nbsp; return (&nbsp; &nbsp; <div className="product">&nbsp; &nbsp; &nbsp; <button className="add_card" onClick={() => addProduct()}>&nbsp; &nbsp; &nbsp; &nbsp; {" "}&nbsp; &nbsp; &nbsp; &nbsp; add to cart&nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; </div>&nbsp; );};const mapDispatchToProps = dispatch => {&nbsp; return {&nbsp; &nbsp; addProduct: (product) => {&nbsp; &nbsp; &nbsp; dispatch(addProduct(product))&nbsp; &nbsp; }&nbsp; }};export default connect(null, mapDispatchToProps)(({ products = [], ...rest }) =>&nbsp; products.map((product, i) => {&nbsp; &nbsp; return <ProductListItem key={i} product={product} {...rest} />;&nbsp; }))动作创建者export const addProduct = () => {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; type: "Woof"&nbsp; &nbsp; }}您可能已经对 action-creator 进行了格式错误并使其成为普通对象而不是返回对象的函数。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答