此错误消息中的 'move this variable directly inside useEffect' 是什么意思?

What does it mean to 'move this variable directly inside useEffect' in this error message?

我试图通过道具将对象传递给子组件。该值在 useEffect 挂钩中设置,并在传递给我的子组件时丢失。

我已经尝试在一个单独的函数中设置 useEffect 挂钩之外的对象的值,但该值仍然丢失。

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

function SetValue(props){

    let users = {};

    useEffect(() => {
          users = { user: 'bob' };
    })        

    return <NewComponent users={users} />
}

export default SetValue;

我希望 props.users 是 { user: 'bob' } 而不是空对象 {}。

错误信息是:

"Assignments to the 'users' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect react-hooks/exhaustive-deps"

关于useEffect挂钩:

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. more

这意味着 useEffect 中的函数将在组件渲染后调用。这就是为什么你有一个空对象。

关于错误。你有它是因为 React 不记得你的 users 变量——它将在 SetValue 组件的每个渲染器上重新创建。最好使用 useState 钩子在 useEffect 中设置值并在下一次渲染时记住它。

还有一张纸条。不要忘记将 useEffect 中的第二个参数与依赖项数组一起传递。现在你的钩子将在每次渲染 SetValue 组件后被调用。

这里是如何使用 useState 钩子:

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

function SetValue(props){

    const [users, setUsers] = useState({});

    useEffect(() => {
          setUsers({ user: 'bob' });
    }, [
       //here you could pass dependencies, or leave it empty to call this effect only on first render
    ]);        

    return <NewComponent users={users} />
}

export default SetValue;

这个警告——“从 React Hook useEffect 内部对 'users' 变量的赋值将在每次渲染后丢失——是 React 中存在状态概念的原因。React 组件不保留值在连续 re-renders(组件生命周期)中的正常 javascript 变量。这就是反应状态的帮助,以便状态的变化可以反映在 DOM 中,如果组件 re-renders。