繁体   English   中英

为什么在 useState 挂钩中使用 const 时不显示错误

[英]Why it is not showing error, when using const in useState hook

这是我完整的 React js 代码。 我在“const [name, setName] =useState('Micheal');”中使用 const。 当我使用 setName function 更改名称时,它没有显示错误。 由于 javascript 中的 const 表示,它不能改变,为什么它没有显示任何错误

import React,{useState} from "react"
import ReactDOM from 'react-dom'
function Emp(){
  const [name,setName]=useState("Micheal");
  const [id,setId]=useState(1024);
  const [age,setAge]=useState(23);
  const handleClick=()=>{
    setName("Jackson");
    setId(2021);
    setAge(29);
  }
  return (
    <>
    <h1>Emp Details</h1>
    <h1>your name: {name}</h1>
    <h1>your id: {id}</h1>
    <h1>your age: {age}</h1>
    <button type="button" onClick={handleClick}>Click Here</button>
    </>
  );
}
ReactDOM.render(<Emp/>,document.getElementById('root'));

const表示不能重新分配标识符。 (不要与不可变值混淆。与真正的不可变数据类型(例如由 Immutable.js 和 Mori 生成的数据类型)不同,一个const object 可以具有改变的属性。)

来自: https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75

例如:

 const obj1 = {}; obj1.a = '12345' console.log(obj1)

从 React 文档中查看这个示例: https://reactjs.org/docs/hooks-state.html#recap

具体来说,这一行: Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it. Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.

例如,每次调用 setId 时,useState 都会为 id 返回一个新值,并重新渲染您的组件。 它不仅仅是分配一个变量 - useState 有副作用,而且不仅仅是分配一个值。

这并不违反const的使用,因为 useState 在技术上返回一个新初始化的值并使用该值重新渲染。 它不是双重分配、重命名或类似的东西。

最后, const还可以防止您错误地重新分配组件中的 useState 变量。

setState是 React 的 API 钩子,我们这样称呼它: const [name, setName] =useState('Micheal');

and this is destructuring assignment, name is a constant referencing to object behind state called Micheal by you and setName is a function to notice to React state that the Micheal will have change and the Micheal will have new value after that, this way the whole component将再次渲染...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM