使用反应路由器重定向

时间:2017-05-22 16:52:07

标签: javascript reactjs redirect react-router

如果帖子请求成功,我正在使用ReactJS并且有一个需要重定向到另一个组件的表单(组件)。我刚开始使用react路由器,所以这就是我尝试重定向的方式。

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect, Link } from 'react-router-dom';
import NextComponent from '/NextComponent';
import axios from 'axios';

class CurrentComponent extends Component {

constructor() {
    super();
    this.state = {
        value: ''
        redirect: false
    };
}

handleSubmit() {
    axios.post('xxx/yyy', {
        xxx: yyy
    })
    .then(function() {
        console.log('Success');
        this.setState({redirect: true});
    })
    .catch(function() {
        console.log('Error');
    });
}

render() {
    return(
        <div>
         <form>
          <div className="form-group">
           <input type="name" placeholder="name" />
          </div>
          <div className="form-group">
          <button type="button" onClick={this.handleSubmit.bind(this)} >Submit</button>
          {this.state.redirect &&
           <Redirect to={{
            pathname: '/nextcomponent',
            state: {from: this.state.value}
            }} />
          }
       </div>
         <Router>
           <Route path="/nextcomponent" component={NextComponent} />
         </Router>
        </form>
       </div>
    );
 }
}

export default PresentComponent;

它没有重定向,我一直试图解决这个问题。我相信有更好的解决方案,但由于我缺乏知识,我不确定是否可以实施。任何帮助表示赞赏。谢谢。

6 个答案:

答案 0 :(得分:1)

这对我的用例不太有用。试试这个 -

<Route exact path="/some_url" render={() => (
  submitted ? (
    <Redirect to="/profile"/>
  ) : (
    <HomePage/>
  )
)}/>

修改你的逻辑或将其封装到<Route />中,如本例所示。

答案 1 :(得分:1)

如果您正在使用react-router 4,则可通过上下文获取历史记录:

this.context.history.push('/some/Path');

所以你要修改你的handleSubmit:

handleSubmit() {
    axios.post('xxx/yyy', {
        xxx: yyy
    })
    .then(function() {
        console.log('Success');
        this.context.history.push('/go/somewhere/else');
    })
    .catch(function() {
        console.log('Error');
    });
}

有关在没有条件路由的情况下更改历史记录的其他方法,请参阅this answer

答案 2 :(得分:1)

在发布电话后,您可能无法获得state,请尝试将handleSubmit方法修改为:

handleSubmit() {
    let _this = this;
    axios.post('xxx/yyy', {
        xxx: yyy
    })
    .then(function() {
        console.log('Success');
        _this.setState({redirect: true});
    })
    .catch(function() {
        console.log('Error');
    });
}

根据新代码更新:

class ComponentOne extends Component {

    constructor() {
        super();
        this.UpdateRoute= this.UpdateRoute.bind(this);
        this.state = {
            value: ''
        };
        this.loggedin = false;
    }

    const UpdateRoute = () => (
        <Router>
        <Route exact path="/xyz" render={() => (
          loggedin ? (
            <ComponentTwo />
          ) : (
            <ComponentOne />
          )
        )}/>
        </Router>
    )

    handleSubmit() {
        let _this = this;
        axios.post('/xyz', {
            xxx: yyy,
        })
        .then(function(response) {
            _this.loggedin = true;
            _this.UpdateRoute();
        })
        .catch(function() {
            console.log('Error');
        });
    }

    render() {
        return(
              <div>
            <h1>Load First</h1>
            <button type="button" onClick={this.handleSubmit.bind(this)}>Submit</button>
              </div>
        );
    }
}

export default ComponentOne;

答案 3 :(得分:0)

如果您使用的是React-router-dom,请查看下面给出的链接。

https://reacttraining.com/react-router/web/example/auth-workflow

答案 4 :(得分:0)

Redirectreact-router而不是react-router-dom的导出。因此,您需要将其导入为:

import { Redirect } from 'react-router'

Redirect doc

答案 5 :(得分:0)

使用react-router 2.8

我使用react-router中的hashHistory来实现这个

import { hashHistory } from 'react-router';

然后我想重定向:

hashHistory.push('/go/somewhere/else');
相关问题