日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

工程級?React?注冊登錄全棧級流程分析_React

作者:Touryung's?Blog ? 更新時間: 2023-05-20 編程語言

創建前端項目

npm install create-react-app -g
create-react-app my-app-client

create-react-app 是創建單頁面程序的腳手架

前端目錄結構

創建好項目之后,刪掉 src 目錄下的文件,按照以下結構創建目錄,根據具體項目情況進行更改

引入 UI 組件庫

npm install antd -S

Ant Design 是企業級的 UI 設計語言和 React 組件庫

引入路由

npm install react-router-dom -S

使用路由進行不同頁面間的切換

使用示例:

ReactDOM.render(
  <Provider store={store}>
    <HashRouter>
      <div className="container">
        <Switch>
          {routes.map((route) => (
            <Route key={route.path} {...route} />
          ))}
        </Switch>
      </div>
    </HashRouter>
  </Provider>,
  document.getElementById("root")
);

routes/index.js 中,引入需要的組件并導出路由配置對象

import Register from "../pages/register/Register";
import Login from "../pages/login/Login";
import Main from "../pages/main/Main";

export const routes = [
  {
    path: "/register",
    component: Register,
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "",
    component: Main,
  },
];

引入 redux

npm install redux react-redux redux-thunk -S
npm install redux-devtools-extension -D

注冊組件樣式

示例:

<Layout>
  <Header>
    <Logo />
  </Header>
  <Content>
    <Input type="text"/>
  </Content>
  <Footer>
    <Button type="primary">注冊</Button>
  </Footer>
</Layout>

在自己想要使用 antd 的組件中可使用 import {} from "antd" 即可引入組件樣式,任意使用

收集注冊數據

數據通過 state 儲存,通過綁定輸入框 onChange 事件更新數據

state = {
    username: "",
    password: "",
    againPassword: "",
    type: "",
  };
handleChange = (name, value) => {
    this.setState({
      [name]: value,
    });
  };

完成登錄組件

和注冊組件相同的方式完成登錄組件

注意:注冊和登錄組件中的路由跳轉使用 this.props.history 中的 replace() 或者 push() 方法實現,區別是 replace 不能回退,push 可以回退

創建后端項目

express myapp-server -e

修改 bin/www 中的端口號為 4000,避免與前端的監聽端口號 3000 沖突

使用 Postman 測試接口

自動重啟后端工具

npm install nodemon -D

安裝之后將 package.json 中的 scripts.start 改為 nodemon ./bin/www,啟動之后每次修改代碼保存即可立即重啟

使用 mongodb

npm install mongoose blueimp-md5 -S

常見操作:save,find,findOne,findByIdAndUpdate,delete(remove 已經過時)
blueimp-md5 庫用來對密碼進行 md5 加密,庫導出的是函數,直接使用 blueimp-md5(password)即可返回加密結果

編寫數據庫操作模塊

使用操作 mongodb 數據庫的 mongoose 模塊向外暴露一個數據庫操作的類,這樣在路由中如果需要操作數據庫只需要引入類直接使用

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/school-chat");
const connection = mongoose.connection;
connection.on("connected", () => {
  console.log("數據庫連接成功");
});

const userSchema = mongoose.Schema({
  username: { type: String, required: true },
  password: { type: String, required: true },
  type: { type: String, required: true },
  ...
});
const UserModel = mongoose.model("user", userSchema);

exports.UserModel = UserModel;

后端注冊路由

routes/index.js 中編寫后端所有的路由,路由中返回的對象儲存在前端 ajax 請求的響應體中

注冊首先需要在數據庫中查找用戶是否存在,不存在才新建一條文檔

router.post("/register", (req, res) => {
  const { username, password, type } = req.body;
  UserModel.findOne({ username }, (err, user) => {
    if (user) {
      res.send({ code: 1, msg: `用戶“${username}”已存在` });
    } else {
      const userModel = new UserModel({ username, password: md5(password), type });
      userModel.save((err, user) => {
        res.cookie("userid", user._id, { maxAge: 1000 * 3600 * 24 * 7 });
        res.send({ code: 0, data: { _id: user._id, username, type } });
      });
    }
  });
});

后端登錄路由

登錄首先需要在數據庫中查找用戶是否存在,存在才返回相應的信息

router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne({ username, password: md5(password) }, filter, (err, user) => {
    if (user) {
      res.cookie("userid", user._id, { maxAge: 1000 * 3600 * 24 * 7 });
      res.send({ code: 0, data: user });
    } else {
      res.send({ code: 1, msg: "用戶名或密碼不正確" });
    }
  });
});

前端請求函數封裝

npm install axios -S

主流請求分為 GET 請求和 POST 請求,GET 請求需要根據 data 對象拼接出請求的 url

export default function ajax(url = "", data = {}, type = "GET") {
  if (type === "GET") {
    let queryStr = "";
    for (let key in data) {
      queryStr += `${key}=${data[key]}&`;
    }
    if (queryStr !== "") {
      queryStr = queryStr.slice(0, -1);
      return axios.get(`${url}?${queryStr}`);
    }
  } else {
    return axios.post(url, data);
  }
}

前端接口請求模塊

通過前面封裝的請求函數,將項目中所有用到的請求都封裝成函數在 api/index.js

export const reqRegister = (user) => ajax("/register", user, "POST");
export const reqLogin = (username, password) => ajax("/login", { username, password }, "POST");
export const reqUpdate = (user) => ajax("/update", user, "POST");
...

前端注冊的 redux

redux/actions.js 中編寫多個 action creator:同步 action,異步 action

export const register = (user) => {
  const { username, password, againPassword, type } = user;
  if (!username) {
    return errorMsg("用戶名不能為空!");
  }
  if (password !== againPassword) {
    return errorMsg("兩次密碼不一致!");
  }
  return async (dispatch) => {
    const response = await reqRegister({ username, password, type });
    const result = response.data;
    if (result.code === 0) {
      dispatch(authSuccess(result.data));
    } else {
      dispatch(errorMsg(result.msg));
    }
  };
};

異步 action 分發授權成功的同步 action(請求),在分發之前進行前端驗證,如果失敗就不分發同步 action,直接返回對應的同步 action,因為請求返回的值的類型的 Promise,所以需要使用 es7 中的 async 和 await 關鍵詞,authSuccess 和 errorMsg 同步 action 返回包含 action type 的對象

redux/reducers.js 中編寫所有的 reducer 函數,然后使用 combineReducers 函數結合起來暴露出去

function user(state = initUser, action) {
  switch (action.type) {
    case AUTH_SUCCESS:
      return { ...action.data, redirectTo: "/" };
    case ERROR_MSG:
      return { ...state, msg: action.data };
    default:
      return state;
  }
}

export default combineReducers({
  user,
});

根據老的 user state 和指定的 action 返回新的 state

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import reducers from "./reducers";

export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)));

最后,在 redux/store.js 中暴露編寫 redux 最核心部分,向外暴露 store 對象,代碼比較固定,在大部分項目中幾乎不變

完善登錄和注冊組件

登錄和注冊點擊發送請求的時候會出現瀏覽器跨域報錯,意思是 3000 端口向 4000 端口發送請求
一個簡單的解決辦法是使用代理:在 package.json 中配置 "proxy": "http://localhost:4000",意思是配置一個在 3000 端口可以向 4000 端口轉發請求的代理,瀏覽器識別不出代理

將 redux 作用在在注冊和登錄組件上:

export default connect(
  (state) => ({
    user: state.user,
  }),
  { register }
)(Register);

其中 user 中的狀態可以通過 this.props.user 獲取,比如 this.props.user.msg,然后就可以將 redux 中的狀態展現在組件中

注冊操作可使用 this.props.register(this.state) 進行登錄

原文鏈接:https://www.cnblogs.com/touryung/p/17130118.html

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新