为什么反应钩子改变了状态值?没有 setState?

时间:2021-07-19 18:02:46

标签: reactjs react-hooks react-state react-state-management

我只更改了 const 值...但是,为什么输出是 Hello? 请解释一下...

import React, { useState } from "react";

export default function App() {
    const [value, setValue] = useState(["hi"]);

    const handlePress = () => {
        console.log(value);
        const a = value;
        a[0] = "Hello";
    };

    return (
        <div className="App">
            <button onClick={handlePress}>Press</button>
        </div>
    );
}

1 个答案:

答案 0 :(得分:1)

因为您将一个状态值初始化为一个通过引用调用的数组,所以如果您直接覆盖该值,那么实际值将被覆盖状态不会被更新,所以要更新一个数组,您可以创建一个新的数组并赋值或使用展开操作。

import React, { useState ,useEffect} from "react";

export default function App() {
    const [value, setValue] = useState(["hi"]);

    const handlePress = () => {
        // array are pass by reference so , value reference is passed to a variable and the first element is over riden by value "Hello"
        const a = value;
        a[0] = "Hello";
    };

   useEffect(()=>{
   console.log(value,"check how value changes here")
   },[value])

    return (
        <div className="App">
            <button onClick={handlePress}>Press</button>
        </div>
    );
}