将一个状态与useState挂钩中的另一个状态相关联

时间:2020-05-03 03:11:01

标签: reactjs react-hooks

我想要一个状态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

1 个答案:

答案 0 :(得分:2)

您可以将useEffect和Dependency用作[a]。添加此块,以便a更新时,此useEffect将运行并设置B的值

   useEffect(() => {
        setB(a);
      },[a]);

完整代码:

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [a, setA] = useState("");
  const [b, setB] = useState(a);

  const updateA = () => {
    setA("Hi");
  };

  useEffect(() => {
    setB(a);
  },[a]);

  useEffect(() => {
    console.log("a: ", a);
    console.log("b: ", b);
  });

  return (
    <div className="App">
      <button onClick={updateA}>Update State A</button>
    </div>
  );
}

输出:

a:  "" 
b:  "" 
a:  Hi 
b:  "" 
a:  Hi 
b:  Hi