[英]Why does a simple React Component render twice?
我剛剛開始了一個新的 create-react-app 項目,發現 react 渲染了兩次組件! 我在package.json中的反應版本是"react": "^16.13.1"
import React, { useRef } from "react";
const App = () => {
const renders = useRef(0);
console.log("renders: ", renders.current++);
return (
<div>
Hello
</div>
);
};
這在第一次渲染時產生:
renders: 0
renders: 0
現在,如果我添加一個按鈕來增加 state,每個 state 更改還會產生兩個額外的渲染:
import React, { useRef } from "react";
const App = () => {
const [count, setCount] = useState(0);
const renders = useRef(0);
console.log("renders: ", renders.current++);
return (
<div>
<button onClick={() => setCount(count + 1)}>increment</button>
<div>count: {count}</div>
</div>
);
};
這將導致:
//--- initial render
renders: 0
renders: 0
//--- first click
renders: 1
renders: 2
//--- second click
renders: 3
renders: 4
//--- third click
renders: 5
renders: 6
這是正常的還是最新版本的反應中的錯誤?
好的,看來我找到了原因。 檢查index.js
后,我發現以下內容:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
看起來 create-react-app 現在包括React.StrictMode
,它在開發模式(而不是生產)中雙重調用某些方法。
除了您發現的 StrictMode 問題之外,我認為當您使用這樣的ref
時,它會產生副作用,因此您通常需要將其放入useEffect
以防止它渲染兩次:
import React, { useState, useEffect, useRef } from "react";
const App = () => {
const [count, setCount] = useState(0);
const renders = useRef(0);
useEffect(() => {
// Every time the component has been re-rendered,
// the counter is incremented
console.log("renders: ", renders.current++);
});
return (
<div>
<button onClick={() => setCount(count + 1)}>increment</button>
<div>count: {count}</div>
</div>
);
};
export default App;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.