【问题标题】:How to Redirect to another page in ReactJS when a IF condition is executed?执行IF条件时如何重定向到ReactJS中的另一个页面?
【发布时间】:2018-10-24 01:23:51
【问题描述】:

如果用户名和密码匹配,我想重定向到 Dashboard.jsx。怎么做 ?我是 ReactJS 的新手。

在 If 条件中,我想添加重定向代码来重定向另一个页面。 请回复。在 stackoverflow 中,最大值是在没有 if 条件的情况下使用的,所以这就是区别。

var users={
name:'bddebashis',
password:'debashis111249'
}

class Home extends Component {


constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
}


 handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    fetch('/api/form-submit-url', {
        method: 'POST',
        body: data,
    });

    if(data.get('usr')==users.name && data.get('paswd')==users.password){
      <Redirect to='./Dashboard';/>

    }
  }

【问题讨论】:

标签: javascript reactjs ecmascript-6 react-router


【解决方案1】:
// Are You using BrowserRouter means you can use like this

import PropTypes from 'prop-types';

var users={
    name:'bddebashis',
    password:'debashis111249'
    }

    class Home extends Component {


    constructor() {
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    static contextTypes = {
        router: PropTypes.object,
      }

     handleSubmit(event) {
        event.preventDefault();
        const data = new FormData(event.target);

        fetch('/api/form-submit-url', {
            method: 'POST',
            body: data,
        });

        if(data.get('usr')==users.name && data.get('paswd')==users.password){
          this.context.router.history.push("/Dashboard")  
        }
      }
    }

【讨论】:

  • 非常感谢您,您节省了我的时间。
【解决方案2】:

如果你使用 React Router,你可以使用 Redirect 组件

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md

 <Redirect to="/dashboard" />

在渲染函数中添加重定向组件就足够了。

【讨论】:

    【解决方案3】:
    import createHistory from 'history/createBrowserHistory';
    export const history = createHistory();
    
    <Router history={history}>
       <Route />
    
       <Router>
    

    在您的仪表板组件中 仪表板中的导入历史记录 使用此行重定向

    history.push('/Dashboard');
    

    【讨论】:

      【解决方案4】:

      使用history 模块使重定向变得更容易。安装历史模块npm install history,然后像这样配置您的添加路由器。
      AppRouter.js

      import { Router, Route, Switch } from 'react-router-dom';
      import createHistory from 'history/createBrowserHistory';
      export const history = createHistory();
      
      <Router history={history}>
         <Route path="/about" component={AboutPage} />
         <Route ... />
         ...
      <Router>
      

      然后重定向到另一个component.like

      import {history} from './AppRouter';
      
      history.push('/dashboard');
      

      【讨论】:

        猜你喜欢
        • 2020-08-29
        • 1970-01-01
        • 2019-03-31
        • 2020-06-15
        • 2022-01-04
        • 2020-01-26
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多