当前位置:  开发笔记 > 编程语言 > 正文

Why React Hook useState uses const and not let

如何解决《WhyReactHookuseStateusesconstandnotlet》经验,为你挑选了1个好方法。

The standard way to use a React useState Hook is the following:

const [count, setCount] = useState(0);

However this const count variable is clearly going to be reassigned to a different primitive value.

Why then is the variable not defined as let count?



1> Felix Kling..:

clearly going to be reassigned to a different primitive value

Not really. When the component is rerendered, the function is executed again, creating a new scope, creating a new count variable, which has nothing to do with the previous variable.

Example:

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
推荐阅读
爱唱歌的郭少文_
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有