反应使用效应显示组件的安装2次
我有一个组件名称“ home”,其中有一个带有控制台的使用效率。我只是使用了一个常见的使用效果钩。但是,当我最初渲染页面时,我将获得控制台log 2次,而不是在组件的初始安装中显示。谁能告诉我我的代码发生了什么。代码如下:
import React, { useEffect } from 'react';
const Home = () => {
useEffect(()=>{
console.log("Home component mounted")
})
return (
<div className="container">
<h1 className="h1">Home Page</h1>
</div>
)};
export default Home;
i have a component names "Home" and i have a useEffect inside it which has a console.log("Home component mounted"). I just used a common useEffect hook. But when i initially render the page I getting the console log 2 times instead of showing it in the initial mounting of component. Can anyone tell me whats happening with my code. The code is as follows:
import React, { useEffect } from 'react';
const Home = () => {
useEffect(()=>{
console.log("Home component mounted")
})
return (
<div className="container">
<h1 className="h1">Home Page</h1>
</div>
)};
export default Home;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
之所以发生,是因为在您的应用中处于严格模式。转到index.js并评论严格模式标签。您会发现一个渲染。
这发生是React.strictMode的故意特征。它仅在开发模式下发生,应有助于在渲染阶段找到意外的副作用。
或者,您可以尝试使用此钩子:
uselayouteffect
It's happening because in your app in strict mode. Go to index.js and comment strict mode tag. You will find a single render.
This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.
Or you can try to use this hook :
useLayoutEffect
这是由于React。StrictMode
您不必担心 - 仅仅是Strictmode两次运行效果代码(仅在开发期间,不必担心生产)就能捕获错误和内存泄漏等其他
内容更多: https://reactjs.org/docs/docs/strict-mode.html
态
It is because of React.StrictMode
You don't have to worry- just that StrictMode runs your effect code twice(only during development, don't have to worry about production) to be able to catch bugs and memory leaks among other things
Read more: https://reactjs.org/docs/strict-mode.html
Screenshot here
使用componentDidmount()和componentDidupDate()等效。这意味着,当渲染组件时,useeffect()将被调用两次。如果您只需一次使用useeffect(),则只需添加第二个参数即可。会这样。
希望这对您有帮助!
useEffect() equivalent with componentDidMount() and componentDidUpdate(). This means when rendering your component, useEffect() will be called twice. If you want useEffect() only called one time, you just add the second parameter for it. It will as this.
I hope this helpful for you!