简体   繁体   English

我可以在 useEffect 之外声明一个变量吗? 反应钩子

[英]Can I declare a variable outside of useEffect ? React Hooks

I'm learning React Hooks, and I'm actually using the useEffect method.我正在学习 React Hooks,实际上我正在使用 useEffect 方法。 No problem at all, but I got some warnings about my variable declarations.完全没问题,但是我收到了一些关于我的变量声明的警告。 Here's an example of what I wrote :这是我写的一个例子:

import React, { useRef, useEffect } from 'react';

function App(){
  let containerRef = useRef(null);

  let myVariable;

  useEffect(){
    myVariable = containerRef.children[0];
  }

  return(
    <div className="container" ref={el => containerRef = el}>
        <h1>Hey, I'm Laurie </h1>
        <p> Nice to e-meet you!</p>
    </div>
  )
}

This is just an easy and uncompleted example of what I did, for animating my website with GSAP.这只是我所做的一个简单且未完成的示例,用于使用 GSAP 为我的网站制作动画。 I access to the DOM elements with useRef and I only found this solution.我使用useRef访问 DOM 元素,我只找到了这个解决方案。 But my console write me some warnings, and I'm pretty lost.但是我的控制台给我写了一些警告,我很迷茫。

Warning I got :我得到的警告:

Assignments to the myVariable variable from inside React Hook useEffect will be lost after each render. React Hook useEffect 内部对myVariable变量的赋值将在每次渲染后丢失。 To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property.要随着时间的推移保留该值,请将其存储在 useRef Hook 中,并将可变值保留在 '.current' 属性中。 Otherwise, you can move this variable directly inside useEffect.否则,您可以直接在 useEffect 中移动此变量。

Can someone help me with this issue ?有人可以帮我解决这个问题吗?

when you are using Hook basically you are telling React that your component needs to do something after render.当你使用 Hook 时,基本上你是在告诉 React 你的组件需要在渲染后做一些事情。 React will remember the function you passed, and call it later after performing the DOM updates. React 会记住你传递的函数,并在执行 DOM 更新后调用它。

More Details更多细节

https://reactjs.org/docs/hooks-effect.html#example-using-hooks https://reactjs.org/docs/hooks-effect.html#example-using-hooks

Regarding warning: React doesn't remember your myVariable .关于警告: React 不记得您的myVariable It will be recreated on each render.它将在每次渲染时重新创建。 It will be better to use useState hook to set value in useEffect and remember it on the next render.最好使用useState钩子在 useEffect 中设置值并在下一次渲染时记住它。

Remember one thing always pass the second argument in useEffect with an array of dependencies.请记住,始终将 useEffect 中的第二个参数与依赖项数组一起传递。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM