useState使用const而不是让

useState使用const而不是让

本文介绍了为什么React Hook useState使用const而不是让的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用React的useState Hook的标准方法如下:

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

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

不过,显然会将此const count变量重新分配给其他原始值.

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

为什么变量没有定义为let count?

Why then is the variable not defined as let count?

推荐答案

并非如此.重新呈现组件后,该函数将再次执行,创建一个新的作用域,并创建一个新的count变量,该变量与先前的变量无关.

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.

示例:

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

注意:钩子要复杂得多,实际上并没有像这样实现.这只是为了证明类似的行为.

Note: Hooks are way more sophisticated and are not actually implemented like this. This is just to demonstrate a similar behavior.

这篇关于为什么React Hook useState使用const而不是让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:54