如何在React.js中处理登录重定向到仪表板

时间:2019-04-09 19:43:55

标签: reactjs react-router-dom laravel-mix

我在登录后无法进行重定向。据我了解,Fetch API没有处理此概念。我试图使用React-router-dom,但是它不起作用。我不知道我在做什么。我正在尝试学习基本的反应,开发经过完全认证的应用程序。

我做到了

import {  BrowserRouter as Router, Route, Redirect} from 'react-router-dom';
import Dashboard from './Dashboard';

这是状态

this.state = {
redirect: false, 
username: '', 
l_password: ''
}

Fetch API和setRedirect函数

setRedirect =() =>{
        this.setState({
          redirect: true
        });
      }
      handleLogin =(event) =>{
      event.preventDefault();

      fetch('/oauth/token',
         {
            method: "POST",
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body:`grant_type=password&username=${this.state.username}&password=${this.state.l_password}&client_id=4&client_secret=LT7raDKvPwIUrDFJBISlhpzAXu6cSYiLBGhrUmTm&scope=*`

         }
      )
      .then(response =>
         response.json()

      )
      .then(responseJson => {
          const returnObj = responseJson;
          console.log(returnObj);
          sessionStorage.setItem('resData', JSON.stringify(returnObj));
          console.log(this.state.redirect);
          if(this.state.redirect === true){
               return (
                   <Router><Route path="/dashboard" component={Dashboard} /></Router>
               );
           }
           else{
            <Redirect to="/" />
           }

      });

        this.setState({
            username: '',
            l_password:''
        });
}

表格

 <Form onSubmit={this.handleLogin}>
                                <Form.Group controlId="formBasicEmail">
                                    <Form.Label>Email address</Form.Label>
                                    <Form.Control type="email" placeholder="Enter email"
                                     autofoccus="true"
                                     autoComplete="new-email"
                                     onChange= {this.ChangeText}
                                     name="username"
                                     value={this.state.username}
                                    />
                                </Form.Group>

                                <Form.Group controlId="formBasicPassword">
                                    <Form.Label>Password</Form.Label>
                                    <Form.Control type="password" placeholder="Password" autoComplete="new-password"
                                     onChange= {this.ChangeText}
                                     name="l_password"
                                     value={this.state.l_password}
                                    />
                                </Form.Group>

                                <Button
                                onClick={this.setRedirect.bind(this)}

                                variant="primary" type="submit" size="lg" block>
                                    Login
                                </Button>
                                <Form.Group controlId="formBasicChecbox">
                                    <Form.Check type="checkbox" label="Remember" />
                                   <a href="#" style={{float:'right', marginTop:-23}}>Forgot Password?</a>
                                </Form.Group>
                                <div id="error"></div>
                                <div className="clear-fix"></div>
                                <hr/>

                            </Form>

我打算实现的是如果重定向为true,则将页面重定向到仪表板,否则将主页

enter image description here

4 个答案:

答案 0 :(得分:1)

首先,在满足登录条件之后,将withRouter导入到您的react-router-dom,然后将 this.props.history.push('/ dashboard')添加到handleLogin函数中。

handleLogin =(event) =>{
      event.preventDefault();

      fetch('/oauth/token',
         {
            method: "POST",
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body:`grant_type=password&username=${this.state.username}&password=${this.state.l_password}&client_id=4&client_secret=LT7raDKvPwIUrDFJBISlhpzAXu6cSYiLBGhrUmTm&scope=*`

         }
      )
      .then(response =>
         response.json()

      )
      .then(responseJson => {
          const returnObj = responseJson;
          console.log(returnObj);
          sessionStorage.setItem('resData', JSON.stringify(returnObj));
          ....
          this.props.history.push('/dashboard')

      });


}

在课程结束时,使用Router(您的课程名称)添加导出默认值

要了解更多信息,请查看本教程。 enter link description here

答案 1 :(得分:0)

我想是为时已晚时触发的onclick吗? 尝试在方法handleLogin的开头将其设置为true

handleLogin = (event) => {
    event.preventDefault();

    this.setState({
      redirect: true
    });     

    fetch('/oauth/token',... 

答案 2 :(得分:0)

class App extends Component {render() {
return (
  <div>
    <NavBar />
    <div className="content">
      <Switch>
        <Route path="/products/:id" component={ProductDetails} />
        <Route
          path="/products"
          render={props => <Products sortBy="newest" {...props} />}
        />
        <Route path="/posts/:year?/:month?" component={Posts} />
        <Redirect from="/messages" to="/posts" />
        <Route path="/admin" component={Dashboard} />
        <Route path="/not-found" component={NotFound} />
        <Route path="/" exact component={Home} />
        <Redirect to="/not-found" />
      </Switch>
    </div>
  </div>
);}}

检查此代码。在我做的一个项目中,我使用了react router dom。

使用以下代码导入它:

import { Route, Switch, Redirect } from 'react-router-dom';

我建议您阅读有关路由的更多信息,Mosh Hamedani在youtube以及他的网站上都提供了不错的教程:)

答案 3 :(得分:0)

https://reacttraining.com/react-router/web/api/Redirect

请勿在您的Route函数中返回setRedirect组件。

在您的应用中创建一个Route并设置状态,例如shouldRedirect在您setRedirect的末尾打电话给

.then(responseJson => {
  const returnObj = responseJson;
  console.log(returnObj);
  ...
  setState({shouldRedirect: this.state.redirect})
})

<Router>
  <Route exact path="/" render={() => (
    shouldRedirect ? (
    <Redirect to="/dashboard"/>
    ) : (
    <PublicHomePage/>
    )
  )}/>
</Router>

您还可以在此处查看有效的示例: https://reacttraining.com/react-router/web/example/auth-workflow