zoukankan      html  css  js  c++  java
  • react 会员登录

    会员登录在我们的好多项目中都有用到,比如在后台管理系统,它的第一步就需要你进行登录,还有在我们常见的京东、淘宝、网易云音乐等一系列的软件上面都需要进行登录。

    下面我们直接上代码

     1 fetch(url,{
     2     method: 'post', //使用post方法
     3     mode: 'cors', //跨域
     4     headers:{
     5         'Content-Type': 'application/x-www-form-urlencoded'
     6     },  //请求头
     7     body:'cellphone='+this.state.username+'&password='+this.state.password //方式数据
     8 }).then(res=>res.json())
     9     .then(json=>{if(json.code === 200){
    10         localStorage['uid']=json.data.uid; //本地存储
    11         this.props.history.replace("/detail")
    12     }else {
    13         console.log(json.data)
    14     }})

    现在我们可以看到,我使用的post方法向服务器端发送数据,当请求成功的时候,我们暂时把它存储在本地,这里也可以结合redux来做,有兴趣的可以参考我的另一篇博客初步了解redux来完成,然后进行跳转,如果请求没有成功我们可以直接返回它失败的原因,

    接下来说一下重点,验证它是否登录,我们专门建一个js文件

     1 import React from 'react';
     2 import {Route,Redirect} from 'react-router-dom'
     3 const AuthRoute = ({ component: Component, ...rest }) => (
     4     <Route {...rest} render={props => (
     5         localStorage.getItem("uid") ? (//如果本地存储里面有我们就进行跳转,没有就进行重定向返回登录页面
     6             <Component {...props}/>
     7         ) : (
     8             <Redirect to={{
     9                 pathname: '/news', //重定向的页面
    10                 state: { from: props.location }
    11             }}/>
    12         )
    13     )}/>
    14 );
    15 export {
    16     AuthRoute
    17 }

    最后我们到主路由页面引入我们的这个验证登录

    1 import {AuthRoute} from '../assets/common/function'

    Route改成AuthRoute

    现在我们的会员登录就完成了。

  • 相关阅读:
    1.01 与 0.99 的法则,Python 实现。
    Python list 数据类型:列表
    CDays3 习题一 (处理命令行参数)及相关内容解析。Python getopt 简介
    Arduino 外部中断
    关于普通定时器与高级定时器的 PWM输出的初始化的区别
    电平配配
    C#就地修改字符串
    将DataTable数据转化为Model对象列表
    SQL Server 事件探查器安装
    C语言模拟泛型粘贴符##的使用 迁移
  • 原文地址:https://www.cnblogs.com/nixu/p/9533138.html
Copyright © 2011-2022 走看看