简体   繁体   English

组件渲染两次? 是codeandbox的问题吗?

[英]Is component rendered twice? Is it codesandbox problem?

Here is my simple React-app:这是我的简单 React 应用程序:

let idCounter = 0;

export default function App() {
  const id = useMemo(() => {
    console.log("useMemo");
    return idCounter++;
  }, []);

  console.log("render", id);

  useEffect(() => {
    console.log("useEffect", id);
  });

  return id;
}

https://codesandbox.io/s/morning-bush-swky8 https://codesandbox.io/s/morning-bush-swky8

This is the console output:这是控制台输出:

useMemo
render 0
useEffect 1

Why in useEffect id is equal to 1 ?为什么在useEffect id等于1

Seems like the component has been rendered twice, but why useMemo and useEffect haven't been called for the second time?好像组件已经渲染了两次,但是为什么useMemouseEffect没有被第二次调用呢? How id became 1 ? id怎么变成1 了

From React Docs - Strict Mode:来自React Docs - 严格模式:

Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions.从 React 17 开始,React 自动修改控制台方法,如 console.log() 以在第二次调用生命周期函数时使日志静音。 However, it may cause undesired behavior in certain cases where a workaround can be used.但是,在可以使用变通方法的某些情况下,它可能会导致不希望的行为。

Your component is indeed rendered twice but the log statements are hidden by React during the second re-render caused by StrictMode .您的组件确实被渲染了两次,但在StrictMode引起的第二次重新渲染期间,React 隐藏了日志语句。

You will get the expected output if you remove the StrictMode .如果删除StrictMode您将获得预期的输出。

Another option is to use a different method on console object for logging, such as console.dir .另一种选择是在console对象上使用不同的方法进行日志记录,例如console.dir

 let idCounter = 0; function App() { const id = React.useMemo(() => { console.dir("useMemo"); return idCounter++; }, []); console.dir("render"); console.dir(id); React.useEffect(() => { console.log("useEffect", id); }); return id; } ReactDOM.render( <React.StrictMode> <App/> </React.StrictMode>, document.querySelector("#root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script> <div id="root"></div>

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

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