【问题标题】:making a post request inside mapDispatchToProps in react-redux在 react-redux 中的 mapDispatchToProps 内发出 post 请求
【发布时间】:2021-12-30 21:48:01
【问题描述】:

每当我单击按钮时,我都会尝试在函数内发出发布请求。 这是按钮的代码

<Button onClick={handleClick}>Add to Cart</Button>

这里是`handleClick 函数:

const handleClick = (event) => {

        event.preventDefault(); 
        props.postCart(itemData.product_name, itemData.product_price);
    }

这里我展示了mapDispatchToProps函数的代码:

const mapDispatchToProps = dispatch => {

    return {

        postCart: (productName, productPrice) => dispatch(postAddToCart(productName, productPrice))
    }
}

终于postAddToCart的代码:

export const postAddToCart = (productName, productPrice) => {

    const email = sessionStorage.getItem('email');

    return (dispatch) => {

        dispatch(productName, productPrice);
        //REST API endpoint
        axios.post('http://localhost:8000/api/auth/add-to-cart', {

            email:email, 
            
        })
        .then(resp => {

            dispatch({

                type: actionTypes.ADDED_TO_CART, 
                status: resp.status
            });
        })

        .catch(resp => {

            dispatch({

                type: actionTypes.ADDED_TO_CART, 
                status: "FAILED"
            });
        })

    }

}

但是每当我单击“添加到购物车”按钮时,我都会收到以下错误:

Error: Actions must be plain objects. Use custom middleware for async actions. 知道我正在使用redux-thunk 中间件。

你能告诉我是什么问题吗?我该如何解决?谢谢你^^。如果我错过了什么,请告诉我在 cmets 中添加它^^

【问题讨论】:

  • 你使用redux-thunk中间件了吗?
  • 是的,我用过@slideshowp2

标签: javascript reactjs react-redux


【解决方案1】:

您的函数 postAddToCart() 返回一个“调度程序”,即一个期望 dispatch 作为参数的函数。

错误是你试图调度这个“调度程序”,而不是一个“动作”:

// wrong: calling 'dispatch()'
postCart: (productName, productPrice) => dispatch(postAddToCart( ... ))

// correct: calling the returned dispatcher and pass 'dispatch' as argument
postCart: (productName, productPrice) => postAddToCart( ... )(dispatch)

【讨论】:

  • 我还是有同样的问题
  • dispatch(productName, productPrice); 行是错误的。我不知道那应该做什么,但dispatch 的参数只能是一个“动作”,比如{ type: 'MY_ACTION_NAME', somePayload: 'some value' }
猜你喜欢
  • 2019-04-05
  • 1970-01-01
  • 2021-02-01
  • 2017-02-09
  • 1970-01-01
  • 2020-11-07
  • 2023-03-13
  • 2017-06-23
  • 1970-01-01
相关资源
最近更新 更多