2 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
好的,看來(lái)我找到了原因。檢查后index.js我發(fā)現(xiàn)以下內(nèi)容:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
看起來(lái) create-react-app 現(xiàn)在包括React.StrictMode在開(kāi)發(fā)模式(而不是生產(chǎn)模式)中雙重調(diào)用某些方法。

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
除了您發(fā)現(xiàn)的 StrictMode 問(wèn)題之外,我認(rèn)為當(dāng)您使用ref類(lèi)似的東西時(shí)它會(huì)產(chǎn)生副作用,因此您通常需要將其放入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;
添加回答
舉報(bào)