【问题标题】:How do I use Component props in actionCreators.js?如何在 actionCreators.js 中使用组件道具?
【发布时间】:2021-03-10 00:28:38
【问题描述】:

我目前正在构建亚马逊克隆,但在将商品添加到购物车时尝试更新我的 Redux 商店时遇到了一些问题。当我像这样对我的操作进行硬编码时

// src/redux/actionCreators.js

export const addToCart = () => ({
    type: "ADD_TO_CART",
    item: {
        id: 1,
        title: "book",
        image: "hi",
        price: 420,
        rating: 3,
    }
})

该项目已添加到我的 redux 商店。但是,我想在我的操作创建器中使用我的产品组件中的道具作为 id、标题、图像、价格和评级值。

// src/components/Product.js

import React from 'react';
import '../Product.css';
import { connect } from 'react-redux';
import { addToCart } from '../redux/actionCreators'

const Product = (props) => {
    return (
        <div className="product">
            <div className="product__info">
                <p>{props.title}</p>
                <p className="product__price">
                    <small>$</small>
                    <strong>{props.price}</strong>
                </p>
                <div className="product__rating">
                    {Array(props.rating)
                        .fill()
                        .map((_, i) => (
                            <p>⭐️</p>
                        ))}
                </div>
            </div>
            <img src={props.image} alt={props.title}/>
            <button onClick={ props.addToCart }>Add To Cart</button>
        </div>
    )
}

const mapStateToProps = (state) => ({ cart: state.cart.cart })

export default connect(mapStateToProps, { addToCart })(Product)

这样我的操作看起来像这样

// src/redux/actionCreators.js

export const addToCart = (props) => ({
    type: "ADD_TO_CART",
    item: {
        id: props.id,
        title: props.title,
        image: props.image,
        price: props.price,
        rating: props.rating,
    }
})

但是,道具是未定义的。直接通过动作传递道具将不起作用,那么将我的产品组件道具与动作创建者一起使用的正确方法是什么?

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    而 addToCart 使用这样的功能

     <button onClick={()=> props.addToCart(props) }>Add To Cart</button>
    

    【讨论】:

      猜你喜欢
      • 2019-07-16
      • 1970-01-01
      • 2023-01-31
      • 2019-12-05
      • 2021-08-10
      • 2018-11-21
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多