我只更改了 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>
);
}
答案 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>
);
}