在“ const [isHungry,setIsHungry] = useStatetrue”中,isHungry真的是常数吗?

问题描述

这是一个快速

根据“ https://reactnative.dev/docs/intro-react”

您可能已经注意到,尽管isHungry是一个const,但它似乎可以重新分配!

参考代码

import React,{ useState } from "react";
import { Button,Text,View } from "react-native";

const Cat = (props) => {
  const [isHungry,setIsHungry] = useState(true);

  return (
    <View>
      <Text>
        I am {props.name},and I am {isHungry ? "hungry" : "full"}!
      </Text>
      <Button
        onPress={() => {
          setIsHungry(false);
        }}
        disabled={!isHungry}
        title={isHungry ? "Pour me some milk,please!" : "Thank you!"}
      />
    </View>
  );
}

const Cafe = () => {
  return (
    <>
      <Cat name="Munkustrap" />
      <Cat name="Spot" />
    </>
  );
}

export default Cafe;

根据https://www.w3schools.com/js/js_const.asp

您可以更改常量数组的元素

那么反应文档不正确吗?

解决方法

在react钩子中,const防止在同一范围内重新分配引用的值。因此,渲染后可以将其视为新变量。