Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

reactjs - Updating properties of an object in React with useState

I have this state:

  const [test, setTest] = useState({
    test1: "test",
    test2: "test",
    test3: "test",
  });

useEffect(() => {
    setTimeout(() => {
      setTest({
        ...test,
        test1: "test1",
      });
    }, 2000);

    setTimeout(() => {
      setTest({
        ...test,
        test2: "test2",
      });
    }, 3000);
  }, []);

and I want to get something like:

{
  test1: "test1"
  test2: "test2"
  test3: "test"
}

but I get:

{
  test1: "test"
  test2: "test2"
  test3: "test"
}

Is that possible? What I am doing wrong? Thx

I need to keep this object form, I'm working with APIs and I don't want to have 30 different useStates for each API. I just want to have all fetch API data in one object and use it as a prop.

question from:https://stackoverflow.com/questions/65839206/updating-properties-of-an-object-in-react-with-usestate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a callback instead, so you have the most up-to-date reference to the current test in state, instead of having only a reference to the original (unmodified) test from the initial mount:

setTest(test => ({
    ...test,
    test2: "test2",
}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...