javascript - 為什麼React Hook useState使用const而不是讓
reactjs ecmascript-6 (2)
調用setCount後,將重新呈現組件,並且對useState的新調用將返回新值。 關鍵是計數是不變的。 所以這裡沒有錯字。
從技術上講,它是每個渲染的新變量。
以下是使用React useState Hook的標準方法:
const [count, setCount] = useState(0);
但是,此
const count
變量顯然將重新分配給其他原始值。
為什麼變量沒有定義為
let count
?
顯然將重新分配給其他原始值
並不是的。
重新呈現組件後,該函數將再次執行,創建一個新的作用域,創建一個新的
count
變量,該變量與先前的變量無關。
例:
let _state;
let _initialized = false;
function useState(initialValue) {
if (!_initialized) {
_state = initialValue;
_initialized = true;
}
return [_state, v => _state = v];
}
function Component() {
const [count, setCount] = useState(0);
console.log(count);
setCount(count + 1);
}
Component();
Component(); // in reality `setCount` somehow triggers a rerender, calling Component again
Component(); // another rerender
注意: 掛鉤更為複雜,實際上並未像這樣實現。 這只是為了演示類似的行為。