giayvun
Senior Member
Chào các thím, như em được biết thì các lệnh trong useEffect sẽ được thực thi sau một lần render/re-render. Nhưng có chỗ này em không hiểu sao React lại để dồn useEffect callback của lần re-render thứ hai qua sau khi re-render xong lần thứ ba.
Thím nào hiểu được nguyên nhân hoặc có kiến giải về vấn đề này cho em xin thỉnh giáo, đa tạ rất nhiều
Thím nào hiểu được nguyên nhân hoặc có kiến giải về vấn đề này cho em xin thỉnh giáo, đa tạ rất nhiều
JavaScript:
export default function App() {
const [mock, setMock] = useState("123");
useEffect(() => {
setTimeout(() => {
setMock("456");
}, 3000);
}, []);
return (
<div className="App">
<Test propValue={mock} />
</div>
);
}
JavaScript:
export default function Test({ propValue }) {
const [preValue, setPreValue] = useState(propValue);
count += 1;
console.log("Start render:", count);
useEffect(() => {
console.log("Effect PROP-Change:", { prop: propValue, state: preValue });
}, [propValue]);
useEffect(() => {
console.log("Effect STATE-Change:", { prop: propValue, state: preValue });
}, [preValue]);
useEffect(() => {
console.log("Effect ON-MOUNT");
}, []);
if (preValue !== propValue) {
console.log("Set state handler");
setPreValue(propValue);
}
console.log("Render:", { prop: propValue, state: preValue });
console.log("End render:", count);
console.log("----");
return <div>{propValue}</div>;
}
Sửa lần cuối:


, đã thông não rồi