使用sessionStorage存储元素并在页面刷新时更新状态
我尝试使用 useEffect 挂钩更新状态,但它导致了一些错误。每当进行任何更改时,状态都会更新为 sessionStorage。我尝试在 useEffect 中使用 setElements ,我认为这可能会导致问题。有没有最好的方法来设置和获取 sessionStorage 项目以及更新数组状态。(不使用 redux)。
//This is the initial Element Node which will appear by default at start
let prevElement = [{
id: "0",
type: "input",
data: { label: "Input Node", specificElType: "start" },}]
const DnDFlow = () => {
const [elements, setElements] = useState(prevElement);
...
...
...
//I tried to restore the previous work if stored in sessionStorage
useEffect(() => {
if(JSON.parse(sessionStorage.getItem("flowchart-elements")) != null && JSON.parse(sessionStorage.getItem("flowchart-elements")) != undefined){
setElements(JSON.parse(sessionStorage.getItem("flowchart-elements")));
}});
...
...
...
const onNodeDrag = async (event, node) => {
sessionStorage.setItem("flowchart-elements",JSON.stringify(elements));
}
谢谢
I tried to update the state using useEffect hook and it causing some errors.The state is updated to sessionStorage whenever any changes made. I tried to use setElements in useEffect , I think this might be causing the problem. Is there a best way to set and get sessionStorage item along with updating the array state.(without using redux).
//This is the initial Element Node which will appear by default at start
let prevElement = [{
id: "0",
type: "input",
data: { label: "Input Node", specificElType: "start" },}]
const DnDFlow = () => {
const [elements, setElements] = useState(prevElement);
...
...
...
//I tried to restore the previous work if stored in sessionStorage
useEffect(() => {
if(JSON.parse(sessionStorage.getItem("flowchart-elements")) != null && JSON.parse(sessionStorage.getItem("flowchart-elements")) != undefined){
setElements(JSON.parse(sessionStorage.getItem("flowchart-elements")));
}});
...
...
...
const onNodeDrag = async (event, node) => {
sessionStorage.setItem("flowchart-elements",JSON.stringify(elements));
}
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使
useEffect()
仅在刷新时运行,它需要包含一个空依赖项数组作为其第二个参数,如下所示:For a
useEffect()
to run just on refresh, it needs to include an empty dependency array as its second parameter as shown below: