美文网首页
React项目框架搭建(CRA版本搭建)三

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

作者: importUIKit | 来源:发表于2021-11-24 16:09 被阅读0次

第三章: 全局数据状态管理 Redux

Redux 是啥?

可以理解为全局数据状态管理工具,用来做组件通信等。
好的废话不多说,直接上手。

引入redux 与 react-redux

npm install redux react-redux --save
//o r
yarn add redux react-redux

随后创建store.ts,简单封装个项目可用的store

/src/tools/store/store.ts

store.ts源码如下

import { combineReducers, createStore } from "redux";

export const USER_STATE = 'USER_STATE'; // 用户信息标识
export const MENU_STATE = 'MENU_STATE'; // 菜单信息标识

const initState = {
    user: {},// 用户信息
    menuList: [], // 菜单信息
    recentMenu: [] // 最近使用的菜单
};

const todos = (state = initState, action: any) => {
    switch (action.type) {
        // 用户信息变化
        case USER_STATE:
            return { ...state, user: action.user };
        case MENU_STATE:
            return { ...state, menuList: action.menuList };
        default:
            return state
    }
}

const reducers = combineReducers({
    globalInfo:todos
})

const createMyStore = () => {
    const store = createStore(reducers)
    return store;
}

const store = createMyStore()

export default store;

封装好后,在根目录的index.tsx中调用,代码如下:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import reportWebVitals from "./reportWebVitals";
import "./style/index.less";
import Login from "./pages/login";
import { Provider } from "react-redux";
import store from "./tools/store/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <Login />
    </Provider>
  </React.StrictMode>,
  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();

好了,封装好后,我们回到上一章的Login(登录页中),更新下信息,后续的组件需要用户信息 直接可以获取。

通过useDispatch方法获取dispatch,进行用户信息更新。

import { Form, Input, Button, Checkbox, Card } from "antd";
import cookie from "react-cookies";
import { useDispatch } from "react-redux";
import store, { USER_STATE } from "../../tools/store/store";

const Login = () => {
  const dispatch = useDispatch();
  const changeUser = (values: any) => {
    return { type: USER_STATE, user: { ...values } };
  };
  const onFinish = (values: any) => {
    console.log("Success:", values);
    console.log("cookie:", cookie.load("token"));
    console.log("store:", store.getState()); // 获取state
    // 登录成功
    setTimeout(() => {
      const oneDay = new Date(new Date().getTime() + 24 * 3600 * 1000); // 设置失效日期一天
      cookie.save("token", "ffffffffff", { expires: oneDay });
      //登录更新用户
      dispatch(changeUser(values));
    }, 1000);
  };

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

  return (
    <Card style={{ top: 50, width: "50%", marginLeft: "25%" }}>
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="账号"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
        >
          <Checkbox>记住账号</Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default Login;

到此登录页与状态管理完成。

相关文章

网友评论

      本文标题:React项目框架搭建(CRA版本搭建)三

      本文链接:https://www.haomeiwen.com/subject/enmntrtx.html