简体   繁体   English

React:如何从 useEffect 内部返回 useRef.current.value?

[英]React: How to return useRef.current.value from inside useEffect?

I was planning to use useRef.current.values in a project, and a guide I was reading recommended returning values from inside useEffect.我计划在一个项目中使用 useRef.current.values,并且我正在阅读一份指南,推荐从 useEffect 内部返回值。 The guide showed the setup, but no example for using values.该指南显示了设置,但没有使用值的示例。

I'm stumped on how to get useRef values out of useEffect.我对如何从 useEffect 中获取 useRef 值感到困惑。 I see values inside the pageRef.current object via console.log that get populated after page render.我通过 console.log 在 pageRef.current object 中看到了在页面渲染后填充的值。 useEffect complained when I tried to return the values - the error message says you can only return a function.当我尝试返回值时,useEffect 抱怨 - 错误消息说您只能返回 function。

Here's the Nav component I am using ( Nav is the App entry point and the pages are rendered in PageContainer at the bottom, hookrouter-style):这是我正在使用的 Nav 组件( Nav是 App 入口点,页面在底部的PageContainer中呈现,hookrouter 样式):

const Nav = () => {
    const pageRef = useRef({});
    const [isOpen, setIsOpen] = useState(true);
    const routeResult = useRoutes(directions);

    useEffect(() => {
        if (pageRef.current) {
            let pageHeight = pageRef.current.currentHeight;
            let pageWidth = pageRef.current.currentWidth; // etc.
            console.log(pageRef.current.currentWidth); // example
            return pageWidth; // error, can only return a function
        }
    }, [pageRef]);

    console.log(pageRef.current.clientWidth);

    const backgroundClickHandler = () => {
        if (isOpen) {
            setIsOpen(!isOpen);
        }
  };
  
  const toggleClickHandler = () => setIsOpen(!isOpen);
  
    return (
        <div>
            <ToggleContainer>
                <button
                    className='fas fa-bars fa-2x'
                    onClick={toggleClickHandler}
                ></button>
            </ToggleContainer>
            {isOpen && <NavWrapper>{NavList()}</NavWrapper>}
            <ClickContainer onClick={backgroundClickHandler} isOpen={isOpen}>
                <PageContainer ref={pageRef}>
                    {routeResult || <NotFoundPage />}
                </PageContainer>
            </ClickContainer>
        </div>
    );
};

export default Nav;

So my questions are:所以我的问题是:

  1. Why retrieve useRef values from inside useEffect, instead of directly accessing pageRef.current.value ?为什么从 useEffect 内部检索 useRef 值,而不是直接访问pageRef.current.value Isn't it returning info from the DOM, not updating the DOM directly?它不是从 DOM 返回信息,而不是直接更新 DOM 吗? Returning a current.value a side-effect?返回一个current.value的副作用?

  2. Values inside useEffect for pageRef aren't being updated when resizing the window, even though pageRef is inside the array which useEffect is supposed to watch (?).调整 window 的大小时,不会更新 pageRef 的 useEffect 内的值,即使 pageRef 位于 useEffect 应该监视的数组中(?)。

  3. What's an example of a function to return a pageRef.current.value in this context?在此上下文中返回pageRef.current.value的 function 的示例是什么?

  4. Is there a better way to go about what I'm trying to accomplish here?关于我在这里想要完成的事情,有没有更好的方法来 go ?

Answers to your questions:回答您的问题:

  1. Your useEffect basically says that whenever pageRef changes, call this function.你的useEffect基本上是说每当pageRef发生变化时,调用这个 function。 If done outside, it will call do your tasks on every render instead of doing the whenever pageRef values is changed.如果在外部完成,它将在每次渲染时调用执行您的任务,而不是在pageRef值更改时执行。 Also, in initial renders, it may give undefined values.此外,在初始渲染中,它可能会给出undefined的值。
 useEffect(() => { // called whenever pageRef is changed
        if (pageRef.current) {
            let pageHeight = pageRef.current.currentHeight;
            let pageWidth = pageRef.current.currentWidth; // etc.
            console.log(pageRef.current.currentWidth); // example
        }
    }, [pageRef]);

    console.log(pageRef.current.clientWidth); // called on every render, be it because of pageRef change or not
  1. Values inside pageRef will not change on resizing windows as you have not attached any resize event listeners to the DOM element pageRef 中的值不会在调整 windows 的大小时改变,因为您没有将任何resize事件侦听器附加到 DOM 元素

  2. you can only return a function in useEffect which basically says that before running the same next time, run this function before.你只能在useEffect中返回一个 function ,它基本上说在下次运行之前,先运行这个 function 。 So it perfectly helps in cleanups or unsubscribing from events.因此,它非常有助于清理或取消订阅事件。

  3. You can achieve what you are trying to accomplish with your way, you only need to attach resize event listener to the requrired DOM element and handle the same.您可以通过自己的方式实现您想要完成的任务,您只需要将resize事件侦听器附加到所需的 DOM 元素并进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native如何获取useRef current的值 - How to get the value of useRef current in React Native 如何在没有渲染的情况下在你的本机组件中设置 useRef current.value? - how to setup useRef current.value inside your react native component without render? React useEffect中的间隔 - 将其存储在useRef Hook中以保留值超时警告 - Interval inside React useEffect - store it in a useRef Hook to preserve value overtime warning React:如何防止使用 useRef 和 useState 来跟踪相同的值以防止触发 useEffect? - React: How do I prevent the usage of useRef and useState to keep track of a same value in order to prevent useEffect from triggering? 如何从promise里面返回useEffect - How to return from promise inside useEffect React - 如何在 useEffect 期间 append 将组件反应到 useRef 组件 - React - how to append react component to useRef component during useEffect 即使在 useEffect 中也没有设置 React useRef - React useRef is not setting even in useEffect 反应 useRef / useEffect HTMLCanvasElement 不可分配 - React useRef / useEffect HTMLCanvasElement not assignable 在 useRef 中获取 .current 值 - Get .current value in useRef 在 React 中获取 useEffect 之外的变量的当前值 - Getting current value of variable outside the useEffect in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM