Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Async function in react doesn't react to state change

I want my aysnc function to react to state change so that it can terminate upon state change. What I have discovered is that it doesn't react to changing the state.

In the provided example I am changing the state from inside of the function, however I have tested it and changed the state from outside of function (Button click) and it doesn't work either.

const [testVariable, setTestVariable] = useState(false);

useEffect(()=> {
  testFunction();
}, [])

const testFunction = async () => {
  await timeout(1000);

  console.log("Setting test variable to: " + true);
  setTestVariable(true);

  await timeout(1000);
  
  console.log("Test variable is: " + testVariable);
}

Expected result is to see that the variable changed to true, however what I see is: enter image description here

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

State variables never change their values. (Note that you can, have, and should declare them with const because they don't change).

Subsequent invokes of the component function will get a new state variable with the same name and a different value.

Your testFunction function has closed over the old state variable.


I suspect you could solve this with a reference:

const [testVariable, setTestVariable] = useState(false);
const reference = useRef();
reference.current = testVariable;

… and then have your function test the value of reference.current instead of testVariable.


This does, however, feel like an XY Problem where the real solution is "Use the return value from the function you pass to useEffect to stop whatever it is you want to stop" (and use testVariable as a dependency of useEffect).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...