React项目框架搭建(CRA版本搭建)二

第二章:登录页面以及token存取

创建登录页面Login

/src/pages/login/index.tsx

我这边简单复制下antd示例过来

import { Form, Input, Button, Checkbox, Card } from "antd";

const Login = () => {
  const onFinish = (values: any) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    
记住账号
); }; export default Login;

我们在根目录下的index.tsx使用Login组件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import './style/index.less'
import Login from './pages/login';

ReactDOM.render(
  
    
  ,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

yarn start下运行后看到登录界面

界面完后,需要考虑登录逻辑,token的存取,这里使用react-cookies存储token

引入react-cookies

npm install react-cookie --save
// or
yarn add react-cookie

react-cookies api简单介绍

// 引入
import cookie from 'react-cookies'
// 存
cookie.save(‘token’, "123”,{});
// 取
cookie.load('token’);
// 删除
cookie.remove('token')
// 存数据时设置失效时间
const oneDay = new Date(new Date().getTime() + 24 * 3600 * 1000); 
// 设置失效日期一天
cookie.save("token", "ffffffffff", { expires: oneDay });

我们这里直接在登录成功后调用存token,并且设置失效日期为一天

const onFinish = (values: any) => {
    console.log("Success:", values);
    console.log("cookie:", cookie.load("token"));

    // 登录成功
    setTimeout(() => {
      const oneDay = new Date(new Date().getTime() + 24 * 3600 * 1000); // 设置失效日期一天
      cookie.save("token", "ffffffffff", { expires: oneDay });
    }, 1000);
  };

提示:token是否需要存可以与后端沟通,做的好几个项目都不需要前端对token存储,后端直接存session里面,如果不需要可以不引入react-cookies。

到这里登陆界面与token就完成了,贴下本次的完整的登陆界面代码

import { Form, Input, Button, Checkbox, Card } from "antd";
import cookie from "react-cookies";

const Login = () => {
  const onFinish = (values: any) => {
    console.log("Success:", values);
    console.log("cookie:", cookie.load("token"));

    // 登录成功
    setTimeout(() => {
      const oneDay = new Date(new Date().getTime() + 24 * 3600 * 1000); // 设置失效日期一天
      cookie.save("token", "ffffffffff", { expires: oneDay });
    }, 1000);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    
      
记住账号
); }; export default Login;

你可能感兴趣的:(React项目框架搭建(CRA版本搭建)二)