How would you use the “useState” hook to toggle the value of a boolean variable “isActive”?
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: "const [isActive, setIsActive] = useState(false); setIsActive(!isActive);". useState trả về một mảng hai phần tử, giá trị state hiện tại và hàm set để đổi nó, và destructuring mảng đặt tên cho cả hai. Gọi setIsActive(!isActive) báo React lưu giá trị mới rồi render lại component, lúc đó isActive mang giá trị đã đảo; khi đảo nhiều lần liên tiếp nên dùng dạng cập nhật theo giá trị trước setIsActive(prev => !prev). "const isActive = useState(false); isActive = !isActive;" sai hai lần: isActive lúc này là cả mảng chứ không phải boolean, và gán lại một hằng const sẽ ném TypeError; hơn nữa sửa biến trực tiếp không khiến React render lại. "const isActive = false; setIsActive(!isActive);" sai vì isActive chỉ là biến thường, còn setIsActive chưa từng được khai báo nên báo ReferenceError. "const [isActive] = useState(!false);" chỉ khởi tạo isActive bằng true và bỏ mất hàm set, nên không có cách nào đảo giá trị về sau.
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