cart.js
const Cart = () => {
const cartListing = useSelector(state => state.cartList);
const {cart, loading, error} = cartListing;
const dispatch = useDispatch();
const removeFromCartHandler = (id) => {
dispatch(removeFromCart(id))
}; // =======>>>>> This function needs to dispatch on onclick event but it fire on first time load and does not fire on click
useEffect(() => {
dispatch(cartList());
return () => {
}
},[]);
return(
<button type="button" className="button" onClick={removeFromCartHandler()} >Delete </button>
action.js
const cartList = () => async (dispatch) => {
try {
dispatch({ type: CART_LIST_REQUEST });
const { data } = await axios.get('http://localhost:3001/cart');
dispatch({ type: CART_LIST_SUCCESS, payload: data.data.cartRecords });
}
catch (error) {
dispatch({ type: CART_LIST_FAIL, payload: error.message });
}
};
const removeFromCart = (id) => async (dispatch) => {
try {
dispatch({ type: CART_REMOVE_ITEM, payload: id });
const { data } = await axios.delete(`http://localhost:3001/cart/${id}`);
dispatch({ type: CART_REMOVE_SUCCESS, payload: data });
}
catch (error) {
dispatch({type: CART_REMOVE_FAIL, payload: error.message})
}
};
export { cartList, removeFromCart };
我不知道为什么removeFromCartHandler()在第一次加载时触发,而不是在单击时触发。我希望removeFromCartHandler()这个函数在onclick事件上触发,而不是在第一次加载时触发,因为我也没有在useEffect钩cartList中添加第一次就很好的调度,但是removeFromCartHandler()函数需要在onClick事件上调度。我想我在这里缺少钩子的概念。我是React-redux的新手,并停留在这里。任何帮助都会被申请
答案 0 :(得分:2)
您的onClick处理程序错误。这样做
public static int getNumberOfYears(double targetBalance) {
int years = 1;
double balance = 10000;
while (balance <= targetBalance) {
balance *= 1.05;
years++;
}
return years;
}
答案 1 :(得分:2)
之所以调用它,是因为您正在调用它-将()
放在removeFromCartHandler
调用函数之后。
onClick={removeFromCartHandler()}
答案 2 :(得分:1)
您需要添加更多代码以获得更好的上下文,但是您要做的就是这样
onClick={(e) => removeFromCartHandler(e, item.id)}
您的主函数希望获取ID,您必须以某种方式传递它。 我假设您渲染购物车商品或执行类似操作,无论如何,此实现都不会传递正确的ID。