【发布时间】:2022-01-25 05:03:09
【问题描述】:
一切正常,但不是应有的。我搜索了互联网,但没有找到可能导致此问题的解决方案。据我所知,我所做的一切都是按照“书”做的。
我正在构建一个电子商务页面。在管理页面上,我可以从产品列表中添加/编辑/删除产品。当我删除一个产品时,它会被删除,但我只在刷新页面时看到这个,而不是当我单击删除按钮时。我想在我删除产品时看到该产品从列表中删除。
我尝试使用 window.location.reload(true);在 if 语句中的 useEffect 中。我用其他工作代码多次检查了代码。我尝试了不同的浏览器。它没有帮助。也许,我忽略了一些非常简单的事情。
我的代码如下:
产品列表屏幕
const productDelete = useSelector(state => state.productDelete);
const { loading: loadingDelete, error: errorDelete, success: successDelete } = productDelete;
useEffect(() => {
if (successDelete) {
dispatch({ type: PRODUCT_DELETE_RESET });
}
dispatch(listProducts());
}, [dispatch, successDelete]);
const deleteHandler = (product) => {
if(window.confirm('Are you sure to delete?')){
dispatch(deleteProduct(product._id));
}
};
// some fancy code that maps over the product list and displays it along with the delete button
<button
type="button"
className="small"
onClick={() => deleteHandler(product)}
>
Delete
</button>
删除动作处理程序
export const deleteProduct = (productId) => async (dispatch, getState) => {
dispatch({ type: PRODUCT_DELETE_REQUEST, payload: productId });
const {
userSignin: { userInfo },
} = getState();
try {
await axios.delete(`/api/products/${productId}`, {
headers: { Authorization: `Bearer ${userInfo.token}` },
});
dispatch({ type: PRODUCT_DELETE_SUCCESS });
} catch (error) {
const message =
error.response && error.response.data.message
? error.response.data.message
: error.message;
dispatch({ type: PRODUCT_DELETE_FAIL, payload: message });
}
};
动作减速器
export const productDeleteReducer = (state = {}, action) => {
switch(action.type){
case PRODUCT_UPDATE_REQUEST:
return { loading: true };
case PRODUCT_DELETE_SUCCESS:
return { loading: false, success: true };
case PRODUCT_DELETE_FAIL:
return { loading: false, error: action.payload };
case PRODUCT_DELETE_RESET:
return {};
default:
return state;
}
}
删除路由器
productRouter.delete(
'/:id',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);
if (product) {
const deleteProduct = await product.remove();
res.send({ message: 'Product Deleted', product: deleteProduct });
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
);
export default productRouter;
商店
combine the reducer with the action handler in the store
非常感谢所有帮助。
【问题讨论】:
-
调度了哪些操作以及它们对状态做了哪些更改(redux devtools)?
listProducts操作是否已调度? -
好问题。在 redux 开发工具中,我看到 listProducts 的状态已调度。
标签: react-redux react-hooks react-router