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
171 views
in Technique[技术] by (71.8m points)

javascript - React state is not applied to the correct state before changing route using history.push

I am attempting to apply proper exiting animation using framer motion. The exiting animation will depend on where the user is (the route) and where the user is headed to next (next route). Simply put, I don't want the background to slide away unless the user is going specifically from route A to route D.

To tackle this problem, I've omitted my links away from Link from react-router-dom and implemented useHistory so that I can change the state RIGHT BEFORE the user is directed. The state is aimed to tell the background to transition or not.

The issue: The state is being changed too slowly. It's as if the state is one step behind every time I change routes with this method. For example, if I want the state (bgAnimate) to be true when the user goes from route A to D, it would be false when the page is directed. THEN the state will be true AFTER the user is already directed. As a result, failing animations.

What I've tried: I've tried adding a delay AFTER state change and BEFORE the history.push(). Same issue. Below is the code being executed when user clicked on the link to be directed. The console log will return the OPPOSITE of what it needs to be (because the state is being set too slowly?? not sure).

  // Initialize history
  let history = useHistory()
  const delay = ms => new Promise(res => setTimeout(res, ms));

  // Change state to change background based on where we are now and where we're headed
  const bgAnimateThenRoute = async (button) => {
    if(button === 'bio') {
      setBgAnimate(true)
      await delay(1000)
      console.log(bgAnimate)
      history.push('/')
    } else if(button === 'projects') {
      setBgAnimate(false)
      await delay(1000)
      console.log(bgAnimate)
      history.push('/projects')
    }
  }
question from:https://stackoverflow.com/questions/66051511/react-state-is-not-applied-to-the-correct-state-before-changing-route-using-hist

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

1 Answer

0 votes
by (71.8m points)

Delay did solve the issue. It was just the that the correct state was not being picked up by the console log. Animations work fine.


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

...