Navigating Programmatically in React-Router v4

后端 未结 10 1120
后悔当初
后悔当初 2020-12-02 11:16

I couldn\'t wait and I jumped into using the latest alpha version of react-router v4. The all-new is great in keeping your U

10条回答
  •  無奈伤痛
    2020-12-02 12:07

    The router will add a history object to your component in the props hash. So in your component, simply do:

    this.props.history.push('/mypath')

    Here is a full example:

    In App.js:

    import React from 'react'
    import {BrowserRouter as Router, Route} from 'react-router-dom'
    
    import Login from './Login'
    
    export default class App extends React.Component {
      render() {
        return (
          
            
    ) } }

    In Login.js:

    import React, {PropTypes} from 'react'
    
    export default class Login extends React.Component {
      constructor(props) {
        super(props)
        this.handleLogin = this.handleLogin.bind(this)
      }
    
      handleLogin(event) {
        event.preventDefault()
        // do some login logic here, and if successful:
        this.props.history.push(`/mypath`)
      }
    
      render() {
        return (
          
    ) } }

提交回复
热议问题