如何在reactjs中处理登录重定向到仪表板

问题描述 投票:1回答:4

登录后我遇到了重定向问题。据我所知,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>

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

enter image description here

reactjs react-router-dom laravel-mix
4个回答
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')

      });


}

在类的末尾,添加export default withRouter(类的名称)

有关更多阅读,请查看本教程。 enter link description here


0
投票

我想这是在为时已晚的情况下触发的onclick?尝试在方法handleLogin的开头设置为true

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

    this.setState({
      redirect: true
    });     

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

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>
);}}

检查此代码。在我做的一个项目中,我使用了反应路由器dom。

使用以下代码导入它:

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

我建议你阅读更多关于路由的信息,Mosh Hamedani在youtube和他的网站上做了很棒的教程:)


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

© www.soinside.com 2019 - 2024. All rights reserved.