不使用redux就能创建自定义路由吗?

时间:2018-09-12 17:22:11

标签: javascript reactjs

我有一个Loginscreen.js

df['M'] = df.index.month  #extracting month and years and creating new columns
df['Y'] = df.index.year
df_pivot = df.pivot_table(index=df.Y, columns=df.M, values='ppt') #pivot with these columns, rather than the index

我有Login.js

import React, { Component } from 'react';
import Login from './Login';

class Loginscreen extends Component {
  constructor(props){
    super(props);
    this.state={
      username:'',
      password:'',
      loginscreen:[],
      loginmessage:'',
      isLogin:true
    }
  }
  componentWillMount(){
    var loginscreen=[];
    loginscreen.push(<Login parentContext={this} appContext={this.props.parentContext}/>);
    this.setState({
                  loginscreen:loginscreen
                    })
  }
  render() {
    return (
      <div className="loginscreen">
        {this.state.loginscreen}
      </div>
    );
  }
}
const style = {
  margin: 15,
};
export default Loginscreen;

返回:

enter image description here

我是否可以单独使用此响应来创建条件语句,该条件语句将创建仅当某人成功登录后才能访问的自定义路由?

这是我的import React, { Component } from 'react'; import { Button, Form, Grid, Segment } from 'semantic-ui-react' import axios from 'axios'; import validator from 'Validator'; import InlineError from './components/messages/InlineError'; import UploadScreen from './UploadScreen'; import { BrowserRouter as Router, Route } from 'react-router-dom'; class Login extends Component { constructor(){ super(); this.state={ email:'', password:'', errors: {} } } onChange = (e) => { this.setState({ [e.target.name]: e.target.value }); } validate = () => { if (!this.state.password) this.state.errors.password = "Can't be blank"; if (!this.state.email) this.state.errors.email = "Invalid Email"; return this.state.errors; } onSubmit = (e) => { const errors = this.validate(this.state); this.setState({ errors }); e.preventDefault(); var apiBaseUrl = "http://127.0.0.1:8000/api/auth/login"; var self = this; var payload={ "email":this.state.email, "password":this.state.password } var config = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, withCredentials: false } axios.post(apiBaseUrl, payload, config) .then(function (response) { console.log(response); if(response.status == 200){ console.log("Login successful"); } else if(response.status == 204){ console.log("Username password do not match"); alert("username password do not match") } else{ console.log("Username does not exists"); alert("Username does not exist"); } }) .catch(function (error) { console.log(error); }); } render() { const { email, password, errors } = this.state; return ( <div className='login-form'> <style>{` body > div, body > div > div, body > div > div > div.login-form { height: 100%; } `}</style> <Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'> <Grid.Column style={{ maxWidth: 450 }}> <br /> <br /> <Form size='large' onSubmit={this.onSubmit}> <Segment stacked> <Form.Input type='text' name='email' value={email} onChange={this.onChange} fluid icon='user' iconPosition='left' placeholder='E-mail address' /> { errors.email && <InlineError text={errors.email} />} <Form.Input type='password' name='password' value={password} onChange={this.onChange} fluid icon='lock' iconPosition='left' placeholder='Password' /> { errors.password && <InlineError text={errors.password} />} <Button fluid size='large' type="submit"> Login </Button> </Segment> </Form> </Grid.Column> </Grid> </div> ); } } const style = { margin: 15, }; export default Login;

app.js

我希望只有在有人登录时才能访问“ /上载”路由。我可以这样做吗?

1 个答案:

答案 0 :(得分:0)

这是公开和私有路线的一种方法:

const PrivateRoute = ({ component: Component, ...rest, loggedIn }) => (
  <Route
    {...rest}
    render={props =>
      (loggedIn ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: LOGIN,
            state: { from: props.location },
          }}
        />
      ))
    }
  />
);

const PublicRoute = ({ component: Component, ...rest, loggedIn}) => (
  <Route
  {...rest}
  render={props =>
    (!loggedIn ? (
      <Component {...props} />
    ) : (
      <Redirect
        to={{
          pathname: HOME,
          state: { from: props.location },
        }}
      />
    ))
  }
/> 
)