如何在单击按钮时用钩子和Redux触发API调用

时间:2020-05-22 10:04:53

标签: javascript reactjs react-redux react-hooks

const onYesBtnClick = (event, id) => {

    dispatch(deleteMedicine, id);
    setConfirmModal(!setConfirmModal);
  };

然后我用callEffect尝试相同的代码

  const onYesBtnClick = useCallback(
    (event, id) => {

      dispatch(deleteMedicine, id);
      setConfirmModal(!setConfirmModal);
    },
    // eslint-disable-next-line
    []
  );

deleteMedicine是执行API调用的函数。

   const medList = useSelector((state) => state.medicineReducer.MedicineList);

medList保存来自redux的数据。我可以直接在onyesBtnClick内部访问medList

两个代码都不起作用。这是使用redux和hooks进行按钮单击的API调用的正确方法吗

1 个答案:

答案 0 :(得分:0)

您需要通过调用函数而不是通过传递参数来分派函数

const onYesBtnClick = (event, id) => {
    console.log(medList); // directly access from closure here
    dispatch(deleteMedicine(id)); // call with id
    setConfirmModal(!setConfirmModal);
  };

或使用useCallback,您会这样写

const onYesBtnClick = useCallback(
    (event, id) => {
      console.log(medList);
      dispatch(deleteMedicine(id));
      setConfirmModal(prev => !prev); // using callback here is necessary
    },

    [medList] // add as a dependency here
  );