代码:
https://codesandbox.io/s/amazing-sound-d20rz?file=/src/App.js
环境:
import React, { useState, useEffect } from "react";
import "./styles.css";
function AppRenderLog() {
console.log("app render");
return null;
}
export default function App() {
const [count, setCount] = useState(2);
useEffect(() => {
console.log("do something");
});
setTimeout(() => {
setCount(1);
setCount(1);
setCount(1);
});
console.log("render by setCont(1)");
return (
<div className="App">
{count}
<AppRenderLog />
</div>
);
}
期望输出:
render by setCont(1)
app render
do something
render by setCont(1)
app render
do something
当前输出:
render by setCont(1)
app render
do something
render by setCont(1)
app render
do something
render by setCont(1) // why? re-render App Component but effectCallback not exec, AppRenderLog Component not re-render
// why others not re-render <App />
答案 0 :(得分:0)
我不知道您要完成什么,但是如果您将第二个console.log也放置在一个效果中,则不会使该记录再次重复。
setTimeout
中排队的状态更新。useState(1)
)来进行测试,并且只会看到正在安装的日志集。代码:
import React, { useState, useEffect } from "react";
import "./styles.css";
function AppRenderLog() {
console.log("app render");
return null;
}
export default function App() {
const [count, setCount] = useState(2);
useEffect(() => {
console.log("do something");
});
setTimeout(() => {
setCount(1);
setCount(1);
setCount(1);
});
useEffect(() => {
console.log("render by setCont(1)");
});
return (
<div className="App">
{count}
<AppRenderLog />
</div>
);
}
控制台日志输出
app render
do something
render by setCont(1)
app render
do something
render by setCont(1)
初始状态为1时控制台日志输出
app render
do something
render by setCont(1)