简体   繁体   English

在 React 中使用普通 const 而不是 useState 的含义

[英]Implications of using a normal const instead of useState in React

I was wondering if someone could explain to me the difference between these two usages of state in a React component.我想知道是否有人可以向我解释 state 在 React 组件中的这两种用法之间的区别。 Is there any definite advantage in using useState for this simple usecase?在这个简单的用例中使用 useState 有什么明确的优势吗?

 function userProfile({user}){ const username = user.name; return ( <h1>{username}</h1> ) }

and

 function userProfile({user}){ const [username, setUsername] = useState(); useEffect(() => { setUsername(user.name); }, [user]) return ( <h1>{username}</h1> ) }

When you use the useState hook you initialize the first const variable as a 'piece' of state of that component, allowing react to re-render the component on every change of that piece of state, using in this case the setUsername function.当您使用 useState 挂钩时,您将第一个 const 变量初始化为该组件的 state 的“一块”,允许在每次更改该 state 时重新渲染组件,在这种情况下使用 setUsername ZC15C4252674C1683 So basically in the first case no re-render fires (and the displayed ui does not update its content) even if you declare your variable with let and then reassing it, but in second case you prepare React to re-render every time setUsername gets called updating the ui contents.因此,基本上在第一种情况下,即使您使用 let 声明变量然后重新评估它,也不会触发重新渲染(并且显示的 ui 不会更新其内容),但在第二种情况下,您准备 React 以在每次 setUsername 获取时重新渲染称为更新 ui 内容。

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

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