使用react-router重定向

IT技术 javascript reactjs redirect react-router
2021-05-03 11:37:50

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

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;

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

4个回答

可能您没有收到statepost 调用后,请尝试将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;

这适用于我不确定你的用例。试试这个 -

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

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

如果您使用的是 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');
    });
}

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

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

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