不废话直接代码
目录
App.js
import { useState } from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(0);
const promise = Promise.resolve("hello");
console.log(promise);
promise.then((c) => console.log(c));
return (
<div className="App">
<h1 onClick={() => setCount(count + 1)}>count: {count}</h1>
</div>
);
}
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
rootElement
);
看到每次渲染会打印两次hello,如果去掉index.js里的StrictMode则只会打印一次hello。
官方作者的说法是在StrictMode下的development环境里,会render两次,但是打印promise却只有一次!
更奇怪的是,如果仍然在StrictMode下,将第8行注释掉,第9行注释取消,则只会打印hello一次。这个我暂时无法理解😣
代码:https://codesandbox.io/s/strict-mode-render-twice-gxdick?file=/src/App.js