【发布时间】:2019-07-12 09:47:39
【问题描述】:
我想把这个生命周期方法改写成一个钩子:
componentDidUpdate = prevProps => {
const { notifications, popNotification } = this.props;
if (prevProps.notifications.length >= notifications.length) return;
const [notification] = notifications;
popNotification(notification.id);
this.setState({
open: true,
message: notification.text,
variant: notification.variant,
});
};
我知道我必须使用 useEffect 挂钩,但它直到现在才开始工作。到目前为止,这是我想出的:
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const dispatch = useDispatch();
const popMessage = useCallback(id =>
dispatch(NotificationActions.popNotification(id))
);
const notifications = useSelector(state => state.notifications);
const previousValue = usePrevious(notifications.length);
useEffect(() => {
if (previousValue >= notifications.length) return;
// Extract notification from list of notifications
const [notification] = notifications;
popMessage(notification.id);
// Open snackbar
setSnackbar({
open: true,
message: notification.text,
variant: notification.variant,
});
});
这种尝试不能作为旧方法工作,它比旧方法被调用更多,并且还会抛出TypeError: notification is undefined。另外,如果我在提取通知之前加上if (notifications.length > 0),还是不行。
【问题讨论】:
-
不需要在你usePrevious的useEffect中加上
[value]吗?像这样的东西:useEffect(() => { ... }, [value])。同样在其他useEffect中,我认为您应该将[notifications]添加到您的useEffect中。至少这不应该比旧的更被调用。 -
看看usePrevious这里:usehooks.com/usePrevious
标签: reactjs react-redux material-ui react-hooks