我正在尝试在服务人员更新时显示敬酒通知,但敬酒通知显示两次。看来这是因为useEffect挂钩,但无法理解如何解决问题。
在App.js中
import React, { Fragment, useState, useEffect } from "react";
import * as serviceWorker from "../serviceWorker";
import { useSnackbar } from "notistack";
const App = () => {
const [newVersionAvailable, setNewVersionAvailable] = useState(false);
const [waitingWorker, setWaitingWorker] = useState({});
const { enqueueSnackbar } = useSnackbar();
const onServiceWorkerUpdate = (registration) => {
setNewVersionAvailable(true);
setWaitingWorker(registration && registration.waiting);
}
const updateServiceWorker = () => {
if(waitingWorker) {
waitingWorker.addEventListener("statechange", event => {
if(event.target.state === "activated") {
setNewVersionAvailable(false);
window.location.reload();
}
})
waitingWorker.postMessage({ type: "SKIP_WAITING" });
}
}
const updateAction = () => {
return (
<Fragment>
<Button
className="snackbar-button"
size="small"
onClick={ updateServiceWorker }
>
{ "Update" }
</Button>
</Fragment>
)
}
useEffect(() => {
serviceWorker.register({ onUpdate: onServiceWorkerUpdate });
if(newVersionAvailable) {
enqueueSnackbar("New Update Available!", {
persist: true,
anchorOrigin: {
vertical: "bottom",
horizontal: "center",
},
action: updateAction,
})
}
})
return (...);
答案 0 :(得分:0)
很难从您发布的代码中知道,但是您拥有什么(如果有)道具?就目前情况而言,您的useEffect
将对每次道具更改做出响应。也许您需要添加一个依赖项数组,并且仅在某些属性更改时触发useEffect
。
useEffect(() => {
serviceWorker.register({ onUpdate: onServiceWorkerUpdate });
if(newVersionAvailable) {
enqueueSnackbar("New Update Available!", {
persist: true,
anchorOrigin: {
vertical: "bottom",
horizontal: "center",
},
action: updateAction,
})
}
}, [prop_whose_change_you_want_to_trigger_this_useEffect])
答案 1 :(得分:0)
将newVersionAvailable
添加到效果的依赖项数组中,一旦触发吐司,则将其设置回false,以免再次触发。
useEffect(() => {
serviceWorker.register({ onUpdate: onServiceWorkerUpdate });
if(newVersionAvailable) {
enqueueSnackbar("New Update Available!", {
persist: true,
anchorOrigin: {
vertical: "bottom",
horizontal: "center",
},
action: updateAction,
});
setNewVersionAvailable(false);
}
}, [newVersionAvailable])