如何在单个onClick事件上调度两个redux操作

oxiaedzo  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(129)

在这里,我在按钮单击时调度一个操作,但现在我想在同一按钮上从redux再调度一个操作,而我想调度的操作已经导入到名为totalHandler的顶部,所以我应该如何执行此操作,谢谢:)

import React from "react";
import { useParams } from "react-router-dom";
import "./ProductDetail.css";
import { useDispatch, useSelector } from "react-redux";
import { cartHandler } from "../../store/DataStore";
import { totalHandler } from "../../store/DataStore";
const Detail = () => {
  const { id } = useParams();
  const dispatch = useDispatch();
  let data = useSelector((state) => state.data.DUMMY_DATA);
  data = data.filter((val) => val.product_id === id);
  data = data[0];
  return (
    <div className="detail_wrapper">
      <div>
        <img src={data.product_image} alt="" className="detail_image" />
      </div>
      <div className="inner">
        <div className="detail_title">{data.product_title}</div>
        <div className="detail_description">{data.product_description}</div>
        <div className="detail_price">{data.product_price}</div>
        <button
          className="button"
          onClick={() => dispatch(cartHandler(data.product_id))}
        >
          Add to Cart
        </button>
      </div>
    </div>
  );
};

export default Detail;
zaq34kh6

zaq34kh61#

<button className="button" onClick={()=>{dispatch(cartHandler(data.product_id));dispatch(totalHandler())}}>Add to Cart</button>

或创建一个函数,如

function Dispatch(){
    dispatch(totalHandler());
dispatch(cartHandler(data.product_id));
}

<button className="button" 
onClick={Dispatch}>Add to Cart</button>
qq24tv8q

qq24tv8q2#

只要在合适的地方加上braquet {}

import React from "react";
import { useParams } from "react-router-dom";
import "./ProductDetail.css";
import { useDispatch, useSelector } from "react-redux";
import { cartHandler } from "../../store/DataStore";
import { totalHandler } from "../../store/DataStore";
const Detail = () => {
  const { id } = useParams();
  const dispatch = useDispatch();
  let data = useSelector((state) => state.data.DUMMY_DATA);
  data = data.filter((val) => val.product_id === id);
  data = data[0];
  return (
    <div className="detail_wrapper">
      <div>
        <img src={data.product_image} alt="" className="detail_image" />
      </div>
      <div className="inner">
        <div className="detail_title">{data.product_title}</div>
        <div className="detail_description">{data.product_description}</div>
        <div className="detail_price">{data.product_price}</div>
        <button
          className="button"
          onClick={() => {dispatch(cartHandler(data.product_id)); 
           dispatch(cartHandler(data.product_id_2))}}
        >
          Add to Cart
        </button>
      </div>
    </div>
  );
};

export default Detail;

相关问题