【问题标题】:redirect using react router使用反应路由器重定向
【发布时间】:2017-10-22 10:19:09
【问题描述】:

如果发布请求成功,我正在使用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;

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

【问题讨论】:

  • 我认为问题在于您正在向重定向添加状态道具,但根据文档,重定向没有状态道具。 reacttraining.com/react-router/web/api/Redirect
  • 是的,谢谢,我已经更改了大部分基于它的逻辑,但是因为示例非常简洁。我觉得很难。

标签: javascript reactjs redirect react-router


【解决方案1】:

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

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

修改您的逻辑或将其封装到 &lt;Route /&gt; 中,如本例所示。

【讨论】:

  • 我试过了,它路由到新路径,但同时显示了两个组件。
【解决方案2】:

如果你使用 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,了解其他无需条件路由即可更改历史记录的方法。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      可能您在调用后没有得到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;
      

      【讨论】:

      • 谢谢,但是通过这种方法,我得到了 2 个组件。我稍微修改了代码。您可以在gist.github.com/anika-sharma/13c79cb40bd53c6e8f7afca634d9a5fb 中看到它。但是现在点击登录变量的值并没有改变。
      • @Annie 检查我更新的答案也尝试在这里查看类似的实现 - aggarwalarpit.wordpress.com/2017/05/15/handling-events-in-react
      • this.UpdateRoute= this.UpdateRoute.bind(this);给出错误无法读取未定义的属性绑定。
      • @Annie 检查更新的答案,UpdateRoute 应该在组件本身中定义。
      • 好的,我已经添加了,但是我的服务器出现故障。我认为在另一个组件中定义一个组件会导致这个问题。
      【解决方案5】:

      Redirect 是 react-router 的导出,而不是 react-router-dom。因此,您需要像这样导入它:

      import { Redirect } from 'react-router'
      

      Redirect doc

      【讨论】:

        【解决方案6】:

        使用 react-router 2.8

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

        import { hashHistory } from 'react-router';
        

        然后我要重定向的地方:

        hashHistory.push('/go/somewhere/else');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-30
          • 1970-01-01
          • 2020-10-22
          • 1970-01-01
          • 2016-10-10
          • 1970-01-01
          • 1970-01-01
          • 2016-11-22
          相关资源
          最近更新 更多