reactjs - React hooks:显示通知的钩子方式
问题描述
我正在做一个项目,我有一个要求,那就是显示通知。
所以我正在使用反应钩子 useEffect 来做到这一点。
下面是我正在尝试做的事情。
const showNotification = useSelector(
state => state.showNotificationInfo
);
useEffect(() => {
if (showNotification.message !== null && showNotification.description !== null ) {
const args = {
message: showNotification.message,
description: showNotification.description,
duration: 0
};
notification.open(args);
}
}, [showNotification]);
在上面的代码中,我获取了 redux 的 showNotificationInfo 值并将其存储在名为 showNotification 的变量中。默认情况下它将为空。
因此,每当 showNotification 除了 null 发生变化时,我都想显示通知。
但是我的问题是即使状态为空,它也会显示带有空值的通知。我不确定我在哪里犯错。任何人都可以请建议我一个更好的方法或者如果可能的话纠正我。
编辑1:
还原状态
const initialState = {
...
...
...
showNotificationInfo: {
message: null,
description: null,
status: null
}
};
export default function(state = initialState, action) {
switch (action.type) {
case SET_NOTIFICATION_INFO:
return {
...state,
showNotificationInfo: {
...state.showNotificationInfo,
message: action.payload.title,
description: action.payload.message,
status: action.payload.status
}
};
}
}
编辑2:
组件代码:
import React, { Fragment, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { notification } from "antd";
const ShowNotificationsComponent = () => {
const showNotification = useSelector(
state => state.showNotificationInfo
);
useEffect(() => {
if (showNotification.message !== null && showNotification.description !== null) {
const args = {
message: showNotification.message,
description: showNotification.description,
duration: 0
};
notification.open(args);
}
}, [showNotification]);
return (
<Fragment></Fragment>
);
};
export default ShowNotificationsComponent;
编辑 3:
动作创建者代码
所以在这里我要做的是每当我按下一个按钮时,这个动作创建者将被调用并将redux状态(即showNotificationInfo)设置为null,并且从后端我将获得新的通知值并将新的通知值发送到商店。
export const moveToMyList = () => dispatch => {
const setMoveToListInfoToNull = {
message: null,
description: null,
status: null
};
dispatch({
type: SET_SHOW_NOTIFICATION_INFO,
payload: setMoveToListInfoToNull
});
return axios({
method: "post",
url: API_URL
})
.then(res => {
const moveToMyListInfo= {};
moveToMyListInfo["title"] = res.data.message;
moveToMyListInfo["message"] = res.data.description;
moveToMyListInfo["status"] = res.data.status;
dispatch({
type: SET_SHOW_NOTIFICATION_INFO,
payload: moveToMyListInfo
});
})
.catch(e => {
console.log(e.response);
});
};
我正在使用的这个通知组件是一个子组件。即使父组件重新渲染,无论 redux 状态如何,都会显示此通知组件(子组件)。
解决方案
showNotification
是一个对象,所以你不能只检查它是否为空(x === null)。你可以做showNotification.message === null
推荐阅读
- javascript - 如何在不影响性能的情况下将大量数据加载到数据表中
- wildcard - AEM 6.4:在过滤器定义中使用通配符
- julia - Julia 的微分方程步长控制
- sql - 表分区 - 保留基本和分区孩子?
- jdbc - 将 Google 表单数据复制到 Cloud SQL
- typescript - 无需导入即可使用类型和接口
- javascript - 覆盖在不同文件中为 Mocha 声明的模拟对象
- asp.net-mvc - 剑道编辑器需要从数据库/本地文件夹中显示图像
- unity3d - 对在游戏过程中只有一侧可见的 2d 纹理使用四边形而不是精灵?
- node.js - 在 Netlify 上设置 Mailjet lambda