v4进行身份验证后导航到页面

v4进行身份验证后导航到页面

本文介绍了使用React Router v4进行身份验证后导航到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过成功的身份验证从login.js导航到app.js.使用路由器v3和浏览器历史记录,我能够相对容易地做到这一点.我不太确定如何使用路由器v4导航页面,因为它们的方法似乎非常不同,并且我以前使用的方法不再有效.我尝试引用此帖子在React-Router v4中以编程方式导航,但是建议没有为我工作.关于如何使用v4遍历应用程序中的页面的任何建议?

I'm trying to navigate to app.js from login.js upon successful authentication. I was able to do this relatively easy using router v3 and browserhistory. I'm not really sure how to navigate pages using router v4 as their methodology seems to be very different and the previous method I used no longer works. I tried referencing this post Navigating Programatically in React-Router v4, but the suggestions didn't work for me. Any advice on how how I can traverse pages in my app with v4?

这是一个电子应用程序

Index.js

import { HashRouter as Router } from 'react-router-dom';
import React from 'react';
import ReactDOM from 'react-dom';
import { Switch, Route } from 'react-router';
import { BrowserRouter } from 'react-router-dom'

import Login from './screens/Login';
import App from './App';


const Application = () => (
  <Router>
    <App />
  </Router>
);

ReactDOM.render(<Application />, document.getElementById('root'));

Login.js

'use strict';

import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import { Route, Router } from 'react-router-dom';
import { matchPath, withRouter, browserHistory} from 'react-router';




class Login extends React.Component{
  constructor(context){
      super(context);
      this.state = {
        email:'',
        password:'',
        err:'',
        loader: 0
      };



      this.handleEmailChange = this.handleEmailChange.bind(this);
      this.handlePasswordChange = this.handlePasswordChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
  }

  focusEmptyInput(){
    //Focus prvog praznog inputa
    for (var ref in this.refs) {
      if(this.state[ref] === ''){
        this.refs[ref].focus();
        break;
      }
    }
  }
  handleNameChange(e){
    this.setState({name: e.target.value});
  }
  handleEmailChange(e){
    this.setState({email: e.target.value});
  }
  handlePasswordChange(e){
    this.setState({password: e.target.value});
  }
  handleSubmit(e){
    e.preventDefault();

    const email = this.state.email.trim();
    const password = this.state.password.trim();

    //Provjeri prazne inpute i focus na prvi prazan
    if((email === '')||(password === '')){
      this.setState({ err: 'All fields are required.'});
      this.focusEmptyInput();
      return;
    }



    this.setState({ err: ''});


    /** AJAX REST calls............ **/
    const userInfo = {
      email: email,
      pass: password
    };

    this.setState({ loader: 100});



var jsforce = require('jsforce');
var conn = new jsforce.Connection({
  oauth2 : {
    // you can change loginUrl to connect to sandbox or prerelease env.
    loginUrl : 'https://test.salesforce.com',
     clientId : 'empty',
    clientSecret : 'empty',
    redirectUri : 'https://test.salesforce.com/services/oauth2/token',
  }
});
conn.login(email, password, function(err, userInfo) {
  if (err) { return console.error(err,email,password);
 }

  // Now you can get the access token and instance URL information.
  // Save them to establish connection next time.
    var token = conn.accessToken;
  console.log(conn.accessToken);
  console.log(conn.instanceUrl);
  //exports.token = conn.accessToken

  sessionStorage.setItem("token", token);


  console.log("User ID: " + userInfo.id);
  console.log("Org ID: " + userInfo.organizationId);
  // ...

  // I would like to be able to redirect to app.js
   browserHistory.push('../app.js')


})









}
  render(){
    return (
      <div className="login-page">
        <div className="wrapper">
          <form className="login-form" onSubmit={this.handleSubmit}>
              <div className="title">
                  <h1>Login</h1>
                  <p>Please enter your login informations.</p>
              </div>
              <div className={(this.state.err === "") ? "hidden" : "error-message fadeIn"}>
                  <p>{this.state.err}</p>
              </div>
              <input
                  type="text"
                  ref="email"
                  className="form-control"
                  value={this.state.email}
                  onChange={this.handleEmailChange}
                  placeholder="Email"
              />
              <input
                  type="password"
                  ref="password"
                  className="form-control"
                  value={this.state.password}
                  onChange={this.handlePasswordChange}
                  placeholder="Password"
              />
              <button type="submit" className="btn">Login</button>
          </form>
        </div>
      </div>
    );
  }
}





export default Login;

app.js

import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { matchPath, withRouter } from 'react-router';
import {
  Window,
  TitleBar,
  NavPane,
  NavPaneItem,
} from 'react-desktop/windows';

import { Home, Settings } from './screens';
import * as Icons from './assets/icons';


const routes = [{
  path: '/',
  exact: true,
  title: 'Home',
  icon: Icons.welcomeIcon,
  component: Home,
}, {
  path: '/settings',
  title: 'Settings',
  icon: Icons.formIcon,
  component: Settings,
}];


class App extends Component {
  static defaultProps = {
    theme: 'dark',
    color: '#cc7f29',
  }

  render() {
    const { replace, location, theme, color } = this.props; // eslint-disable-line

    return (
      <Window theme={theme} color={color}>
        <TitleBar title="My Windows Application" controls />
        <NavPane openLength={200} push theme={theme} color={color}>
          {routes.map(route => (
            <NavPaneItem
              key={route.path}
              title={route.title}
              icon={route.icon}
              selected={Boolean(matchPath(location.pathname, route.path, {
                exact: route.exact, strict: route.strict,
              }))}
              onSelect={() => {
                replace(route.path);
              }}
              color={color}
              background="#ffffff"
              theme="light"
              padding="10px 20px"
              push
            >
              <Route exact={route.exact} path={route.path} component={route.component} />
            </NavPaneItem>
          ))}
        </NavPane>
      </Window>
    );
  }
}

export default withRouter(App);

推荐答案

通过输入以下内容,我可以在Router v4上正常工作.

I was able to get this working correctly with Router v4 by making the below entries.

class Login extends React.Component{
  constructor(){
      super();
      this.state = {

        redirect: false
      };

     this.handleSubmit = this.handleSubmit.bind(this);

在登录功能中,我使用了此

In my login function I used this

 handleSubmit(){

    // On Success do this...

     this.setState({
     redirect: true
   })
   }.bind(this))
}

然后进入渲染功能.

 render(){

 if (this.state.redirect) {
    return <Redirect to="../app.js" />;
  }

    return (

              </div>
              <button type="submit" onClick={this.handleSubmit} className="btn">Login</button>
              </div>
    );
  }
}

这篇关于使用React Router v4进行身份验证后导航到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:13