redux 在React中执行beforeunload时如何获取get State对象

5us2dqdw  于 2023-02-16  发布在  React
关注(0)|答案(1)|浏览(149)

我尝试将此对象保存到具有beforeunload事件的会话持久化数组中

const { serviceRequest, serviceRequestOriginal, isDirty } = useAppSelector((state) => state.csmRequestDataReducer);

  useEffect(() => {
    
    window.addEventListener("beforeunload", (event) => {
      console.log('beforeunload:' + isDirty);
      console.log(current(serviceRequest));
      console.log('beforeunload:' + isDirty);
      dispatch(persistRequestTab({ currentSRCurrentState: isDirty ? serviceRequest : null, currentSRPreviousState: isDirty ? serviceRequestOriginal : null }));
      console.log("API call before page reload");
    });
    
  }, []);

但是,控制台输出显示serviceRequest = null和isDirty = false。
为什么会这样?我可以修改/修复以获得这些对象/值吗?

trnvg8h3

trnvg8h31#

好吧,所以我不知道这是否是一个完美的解决方案,但它似乎真的很好。
创建事件侦听器时,它会锁定初始状态对象值,使用引用useRef()将解决此问题,只需确保在使用更多useEffects更新状态时更新引用。

const { serviceRequest, serviceRequestOriginal, isDirty } = useAppSelector((state) => state.csmRequestDataReducer);
  const currentSRRef = useRef<ServiceRequest | null>(serviceRequest);
  const currentSROrigRef = useRef<ServiceRequest | null>(serviceRequestOriginal);
  const currentIsDirtyRef = useRef<boolean>(isDirty);
  
  useEffect(() => {
    
    window.addEventListener("beforeunload", (event) => {
      console.log('beforeunload:' + currentIsDirtyRef.current);
      dispatch(persistRequestTab({ currentSRCurrentState: currentIsDirtyRef.current ? currentSRRef.current : null, currentSRPreviousState: currentIsDirtyRef.current ? currentSROrigRef.current : null }));
    });
    
  }, []);

  useEffect(() => {
    currentSRRef.current = serviceRequest;
    currentIsDirtyRef.current = isDirty;
  }, [serviceRequest])

  useEffect(() => {
    currentSROrigRef.current = serviceRequestOriginal;
  }, [serviceRequestOriginal])

相关问题