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调用的正确方法吗
答案 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
);