简体   繁体   English

Redux 操作仅适用于 bindActionCreators

[英]Redux action working only with bindActionCreators

I have simple React & Redux app and I have strange issue.我有简单的 React & Redux 应用程序,但遇到了奇怪的问题。 Here the main files of my project:这里是我项目的主要文件:

Home.js file: Home.js 文件:

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import * as productActions from "../../actions/product";
import { connect } from "react-redux";

class Home extends Component {
    componentWillMount() {
        this.props.actions.getProducts();
    }

    render() {
        const { products, actions } = this.props;
        const cart = products.filter(product => product.addToCart);

        return (
            <div className="home mt-5">
                <div className="row">
                    <div className="col-12">
                        <h2 className="mb-3">Products</h2>
                    </div>
                </div>
                <div className="row mt-3">
                    {products.map(product => (
                        <div key={product.id} className="col-sm-6 col-md-3">
                            <div
                                className="view_details"
                                onClick={() => actions.addToCart(product)}
                            >
                                {product.name}{" "}
                                <u>{product.addToCart ? "Remove" : "Add to Cart"}</u>
                            </div>
                        </div>
                    ))}
                </div>
                <div className="row mt-4">
                    <div className="col-12">
                        <h2 className="mb-3">Cart:</h2>
                        {cart.map(product => (
                            <div key={product.id}>{product.name}</div>
                        ))}
                    </div>
                </div>
            </div>
        );
    }
}

export default connect(
    state => ({
        products: state.product.products
    }),
    dispatch => ({
        actions: bindActionCreators(productActions, dispatch)
    })
)(Home);

actions/product.js file:动作/product.js 文件:

import { FETCH_PRODUCTS_DATA, ADD_TO_CART } from "../types/products";

export const getProducts = () => dispatch =>
    fetch(`data.json`)
        .then(response => response.json())
        .then(response => {
            dispatch({
                type: FETCH_PRODUCTS_DATA,
                payload: response.products
            });
        });

export const addToCart = product => ({
    type: ADD_TO_CART,
    product
});

reducers/productReducer.js file:减速器/productReducer.js 文件:

import { FETCH_PRODUCTS_DATA, ADD_TO_CART } from "../types/products";

const initialState = {
    products: []
};

export default function(state = initialState, action) {
    switch (action.type) {
        case FETCH_PRODUCTS_DATA:
            return {
                ...state,
                products: action.payload.map(product => ({
                    ...product,
                    addToCart: false
                }))
            };
        case ADD_TO_CART:
            return {
                ...state,
                products: state.products.map(product =>
                    product.id === action.product.id
                        ? { ...product, addToCart: !product.addToCart }
                        : product
                )
            };
        default:
            return state;
    }
}

There are more files that is not neccesry to share with you here.还有更多的文件不需要在这里与您分享。 With the code above everything is working as expected, the problem is when I don't use the bindActionCreators method.上面的代码一切都按预期工作,问题是当我不使用 bindActionCreators 方法时。 With the following Home.js file (with mapStateToProps and mapDispatchToProps) only the getProducts action is working well but the addToCart action give me the following error: "Cannot read property 'id' of undefined" in this file: reducers/productReducer.js:20使用以下 Home.js 文件(带有 mapStateToProps 和 mapDispatchToProps),只有 getProducts 操作运行良好,但 addToCart 操作给了我以下错误:“无法读取未定义的属性‘id’”在此文件中:reducers/productReducer.js: 20

Home.js file with mapStateToProps and mapDispatchToProps:带有 mapStateToProps 和 mapDispatchToProps 的 Home.js 文件:

import React, { Component } from "react";
import { getProducts, addToCart } from "../../actions/product";
import { connect } from "react-redux";

class Home extends Component {
    componentWillMount() {
        this.props.actions.getProducts();
    }

    render() {
        const { products, actions } = this.props;
        const cart = products.filter(product => product.addToCart);

        return (
            <div className="home mt-5">
                <div className="row">
                    <div className="col-12">
                        <h2 className="mb-3">Products</h2>
                    </div>
                </div>
                <div className="row mt-3">
                    {products.map(product => (
                        <div key={product.id} className="col-sm-6 col-md-3">
                            <div
                                className="view_details"
                                onClick={() => actions.addToCart(product)}
                            >
                                {product.name}{" "}
                                <u>{product.addToCart ? "Remove" : "Add to Cart"}</u>
                            </div>
                        </div>
                    ))}
                </div>
                <div className="row mt-4">
                    <div className="col-12">
                        <h2 className="mb-3">Cart:</h2>
                        {cart.map(product => (
                            <div key={product.id}>{product.name}</div>
                        ))}
                    </div>
                </div>
            </div>
        );
    }
}


const mapStateToProps = state => {
    return {
        products: state.product.products
    };
};
const mapDispatchToProps = dispatch => {
    return {
        actions: {
            getProducts: () => dispatch(getProducts()),
            addToCart: () => dispatch(addToCart())
        }
    };
};
export default connect(mapStateToProps, mapDispatchToProps)(Home);

Someone can tell me why?有人能告诉我为什么吗?

Thank you!谢谢!

Here is your error这是你的错误

const mapDispatchToProps = dispatch => {
    return {
        actions: {
            getProducts: () => dispatch(getProducts()),
            addToCart: () => dispatch(addToCart())
        }
    };
};

addToCart accepts 1 argument, product . addToCart接受 1 个参数product But when you're not using bindActionCreators , addToCart has no arguments.但是当您不使用bindActionCreatorsaddToCart没有参数。 You're dispatching addToCart{} without any arguments.您在不带任何参数的情况下分派addToCart{} products === undefined and you have error. products === undefined ,您有错误。

To solve, add argument to addToCart .要解决,请向addToCart添加参数。

const mapDispatchToProps = dispatch => {
    return {
        actions: {
            getProducts: () => dispatch(getProducts()),
            addToCart: (product) => dispatch(addToCart(product))
        }
    };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM