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

reactjs - How to emulate window.location with react-router and ES6 classes

I'm using react-router, so I use the <Link /> component for my links throughout the app, in some cases I need to dynamically generate the link based on user input, so I need something like window.location, but without the page refresh.

I found this little note - (https://github.com/rackt/react-router/issues/835) - i tried using this.context.router.transitionTo(mylink) but I'm having issues with context...

which led me to (https://github.com/rackt/react-router/issues/1059), however context returns and empty object, so when I try todo something like: this.context.router.transitionTo(mylink); I get Cannot read property 'transitionTo' of undefined (if I try to do something like set this.context = context within the constructor).

Not to drag on, but I'm also weary of messing too much with context as it is undocumented on purpose as it's still a work in progress, so I've read.

Has anyone come across a similar issue?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

After wasting time with react router, I finally switch to basic javascript.

  1. Create a component for your redirect:

    Route path="*" component={NotFound}

  2. In the component use window.location to redirect:

     componentDidMount() {
          if (typeof window !== 'undefined') {
               window.location.href = "http://foo.com/error.php";
          }
     }
    

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

...