Programmatically navigate using react router

后端 未结 30 2429
無奈伤痛
無奈伤痛 2020-11-21 05:18

With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls t

30条回答
  •  星月不相逢
    2020-11-21 05:28

    EDIT: React Router v6

    I haven't touched React in a while, but want to thank and highlight the comment below by @Shimrit Snapir

    on React-Router 6.0 changed to

    React Router V4

    tl:dr;

    if (navigate) {
      return 
    }
    

    The simple and declarative answer is that you need to use in combination with setState()

    push: boolean - when true, redirecting will push a new entry onto the history instead of replacing the current one.


    import { Redirect } from 'react-router'
    
    class FooBar extends React.Component {
      state = {
        navigate: false
      }
    
      render() {
        const { navigate } = this.state
        
        // here is the important part
        if (navigate) {
          return 
        }
       // ^^^^^^^^^^^^^^^^^^^^^^^
        
        return (
          
    ) } }

    Full example here. Read more here.

    PS. The example uses ES7+ Property Initializers to initialise state. Look here as well, if you're interested.

提交回复
热议问题