【发布时间】:2025-12-06 21:30:01
【问题描述】:
我想要一个状态 B,它的值依赖于状态 A,当状态 A 值更新时,状态 B 值随后更新。
问题正如@Atin Singh 在这里所说的changing multiple states in react js useState() hook
const [x, setX] = useState(0)
const [y, setY] = useState(x) // this is just to initialize an initial value to your state y so it will be once set to the value of x and then it doesn't depends on x//
状态 B 的值初始化为状态 A 的值,并且不依赖于状态 A 的值。
但是有没有办法让状态 B 的值依赖于状态 A 的值呢?
这是简化的代码:
export default function App() {
const [a, setA] = useState("");
const [b, setB] = useState(a);
const updateA = () => {
setA("Hi");
};
useEffect(() => {
console.log("a: ", a);
console.log("b: ", b);
});
return (
<div className="App">
<button onClick={updateA}>Update State A</button>
</div>
);
}
您可以从这里编辑代码: https://codesandbox.io/s/nifty-sun-ml843?fontsize=14&hidenavigation=1&theme=dark
【问题讨论】:
标签: reactjs react-hooks