Reactjs 使用相当于shouldComponentUpdate和componentDidUpdate的钩子将类转换为功能组件
我不熟悉hooks,我在这里遇到了这个示例:它是一个类组件,我正在尝试将它转换为带有hooks的函数。我可以很好地使用它,但原因是我也想学习 我尝试用useEffect实现它,但我没有达到预期效果,因为我仍然只显示一次通知,如果我尝试再次创建todo,例如,它就不会显示Reactjs 使用相当于shouldComponentUpdate和componentDidUpdate的钩子将类转换为功能组件,reactjs,react-hooks,Reactjs,React Hooks,我不熟悉hooks,我在这里遇到了这个示例:它是一个类组件,我正在尝试将它转换为带有hooks的函数。我可以很好地使用它,但原因是我也想学习 我尝试用useEffect实现它,但我没有达到预期效果,因为我仍然只显示一次通知,如果我尝试再次创建todo,例如,它就不会显示 function Notifier(props) { const { notifications, removeSnackbar } = props; const { enqueueSnackbar } = useSna
function Notifier(props) {
const { notifications, removeSnackbar } = props;
const { enqueueSnackbar } = useSnackbar();
const [displayed, setDisplayed] = useState([]);
function storeDisplayed(key) {
setDisplayed([...displayed, key]);
}
console.log(displayed)
notifications.forEach((notification) => {
setTimeout(() => {
// If notification already displayed, abort
if (displayed.indexOf(notification.key) >= 0) return;
// Display notification using notistack
enqueueSnackbar(notification.message, notification.options);
// Add notification's key to the local state
storeDisplayed(notification.key);
// Dispatch action to remove the notification from the redux store
removeSnackbar(notification.key);
}, 1);
});
return null;
}
每当我创建或编辑某些内容时,我都希望显示通知。将依赖项数组作为第二个参数添加到useeffect
useEffect(() => {
//something
};
}, [props.friend.id]); // Only re-subscribe if props.friend.id changes
我的实现的解决方案是缺少未定义的键,因此我所做的是在redux存储中添加该键并将其传递给组件道具
function Notifier(props) {
const { notifications, removeSnackbar } = props;
const { enqueueSnackbar } = useSnackbar();
const [displayed, setDisplayed] = useState([]);
function storeDisplayed(key) {
setDisplayed([...displayed, key]);
}
notifications.forEach((notification) => {
setTimeout(() => {
// If notification already displayed, abort
if (displayed.indexOf(notification.options.key) >= 0) return;
// Display notification using notistack
enqueueSnackbar(notification.message, notification.options);
// Add notification's key to the local state
storeDisplayed(notification.options.key);
// Dispatch action to remove the notification from the redux store
removeSnackbar(notification.options.key);
}, 1);
});
return null;
}
我只是这么做了,但仍然是一样的,而且我注意到显示的总是未定义的