How does state behave when it is set in a React component, as described by "State as a snapshot"?
4 phương ánCó giải thích
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "Setting it does not change the state variable you already have, but instead triggers a re-render". Theo mô hình state as a snapshot (state là ảnh chụp) trong tài liệu React, mỗi lần render, component nhận giá trị state cố định của lần render đó; gọi hàm đặt state không sửa biến đang có mà yêu cầu React render lại, và chỉ ở lần render kế tiếp useState mới trả về giá trị mới, nên nếu ghi log biến ngay sau khi đặt state thì vẫn thấy giá trị cũ. "It immediately changes the state variable you already have." sai vì biến trong lần render hiện tại là hằng của ảnh chụp đó, không bị đổi ngay. "It only changes the state after the component unmounts" sai vì sau khi component bị gỡ thì không còn render nữa; state mới có hiệu lực ngay ở lần render tiếp theo khi component vẫn đang hiển thị. "It directly modifies the DOM without triggering a re-render" sai vì đặt state không chạm trực tiếp vào DOM; React render lại, so sánh qua Virtual DOM rồi mới cập nhật DOM thật.
Cùng phần 6
Find the bug in the following React code: const [items, setItems] = useState([]); const addItem = () => { items.push('new'); setItems(items); };Có lời giảiCâu hỏiWhich is the correct way to consume context in a functional component using the "useContext" hook?Có lời giảiCâu hỏiIn the useEffect hook, how many milliseconds would you wait using setTimeout to perform a side effect after 2 seconds?Có lời giảiCâu hỏiCả 24 câu của chủ đề24 câu