Redux基础知识,Redux部分源码分析(手写)

复合组件通信的两种方案:

  • 基于props属性实现父子组件通信(或具备相同父亲的兄弟组件)
  • 基于context上下文实现祖先和后代组件间的通信(或具备相同祖先的平行组件)

除了以上方案,其实还可以基于公共状态管理(Redux)实现组件间的通信问题!

在React框架中,我们也有公共状态管理的解决方案:

  • redux + react-redux
  • dva「redux-saga 」或 umi
  • MobX

Redux基础知识

Redux 中文官网 - JavaScript 应用的状态容器,提供可预测的状态管理。 | Redux 中文官网

什么是 Redux ?
Redux 是 JavaScript 应用的状态容器,提供可预测的状态管理!
Redux 除了和 React 一起用外,还支持其它框架;它体小精悍(只有2kB,包括依赖),却有很强大的插件扩展生态!
Redux 提供的模式和工具使您更容易理解应用程序中的状态何时、何地、为什么以及如何更新,以及当这些更改发生时,您的应用程序逻辑将如何表现!

我什么时候应该用 Redux ?
Redux 在以下情况下更有用:

  • 在应用的大量地方,都存在大量的状态
  • 应用状态会随着时间的推移而频繁更新
  • 更新该状态的逻辑可能很复杂
  • 中型和大型代码量的应用,很多人协同开发

Redux 库和工具
Redux 是一个小型的独立 JS 库, 但是它通常与其他几个包一起使用:
React-Redux
React-Redux是我们的官方库,它让 React 组件与 Redux 有了交互,可以从 store 读取一些 state,可以通过 dispatch actions 来更新 store!
Redux Toolkit
Redux Toolkit 是我们推荐的编写 Redux 逻辑的方法。 它包含我们认为对于构建 Redux 应用程序必不可少的包和函数。 Redux Toolkit 构建在我们建议的最佳实践中,简化了大多数 Redux 任务,防止了常见错误,并使编写 Redux 应用程序变得更加容易。
Redux DevTools 拓展
Redux DevTools Extension 可以显示 Redux 存储中状态随时间变化的历史记录,这允许您有效地调试应用程序。

redux的基本工作流程如下图

除了redux这五步的核心操作外,我们还需要一些其它的知识做配合,三个组件都需要用到创建的store容器,我们在根组件中,导入store,把他放在上下文中,后期其它组件需要,只要是它的后代组件,都可以通过上下文获取

练习代码

store/index.js

// import { createStore } from '../myredux';
import { createStore } from 'redux';

/* 管理员:修改STORE容器中的公共状态 */
let initial = {
    supNum: 102,
    oppNum: 5
};
const reducer = function reducer(state = initial, action) {
    console.log('state',state);
    console.log('action',action);
    // state:存储STORE容器中的公共状态「最开始没有的时候,赋值初始状态值initial」
    // action:每一次基于dispatch派发的时候,传递进来的行为对象「要求必须具备type属性,存储派发的行为标识」
    // 为了接下来的操作中,我们操作state,不会直接修改容器中的状态「要等到最后return的时候」,我们需要先克隆
    state = { ...state }; //浅拷贝 浅克隆一份 最好是深克隆一下
    // 接下来我们需要基于派发的行为标识,修改STORE容器中的公共状态信息
    switch (action.type) {
        case 'VOTE_SUP':
            state.supNum++;
            break;
        case 'VOTE_OPP':
            state.oppNum++;
            break;
        default:
    }
    // return的内容,会整体替换STORE容器中的状态信息
    return state;
};

/* 创建STORE公共容器 */
const store = createStore(reducer);
export default store;


ThemeContext.js

import React from "react";
const ThemeContext = React.createContext();
export default ThemeContext;


index.jsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import Vote from './views/Vote';
/* 使用ANTD组件库 */
import { ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import './index.less';
/* REDUX */
import store from './store';
import ThemeContext from './ThemeContext';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <ConfigProvider locale={zhCN}>
        <ThemeContext.Provider
            value={{
                store
            }}>
            <Vote />
        </ThemeContext.Provider>
    </ConfigProvider>
);


Vote.jsx(函数组件)

import React, { useContext, useState, useEffect } from "react";
import './Vote.less';
import VoteMain from './VoteMain';
import VoteFooter from './VoteFooter';
import ThemeContext from "../ThemeContext";


//函数组件用store示例
//把“让组件可以更新”的方法放在公共容器的事件池中! !store.subscribe(函数)
// store.subscribe接收一个方法---这个方法要能让组件更新的放在事件池当中 函数组件只要状态改变就组件更新

const Vote = function Vote() {
    const { store } = useContext(ThemeContext);
    // 获取容器中的公共状态
    let { supNum, oppNum } = store.getState();


    /* // 组件第一次渲染完毕后,把让组件更新的方法,放在STORE的事件池中
    let [num, setNum] = useState(0);
    const update = () => {
        setNum(num + 1);
    };
    useEffect(() => {
        store.subscribe接收一个方法(函数),返回一个方法(函数)
         let unsubscribe = store.subscribe(让组件更新的方法)
           + 把让组件更新的方法放在STORE的事件池中
           + 返回的unsubscribe方法执行,可以把刚才放入事件池中的方法移除掉
        let unsubscribe = store.subscribe(update);
        return () => { //会在上一次销毁的时候执行
            unsubscribe(); //方法执行,可以把刚才放入事件池中的方法移除掉
        };
    }, [num]); */
    //每次修改为随机数,第一次渲染完成后
    let [_, setNum] = useState(0);
    useEffect(() => {
        store.subscribe(() => {
            setNum(+new Date());
        });
    }, []);

    return <div className="vote-box">
        <div className="header">
            <h2 className="title">React是很棒的前端框架</h2>
            <span className="num">{supNum + oppNum}</span>
        </div>
        <VoteMain />
        <VoteFooter />
    </div>;
};

export default Vote;

VoteFooter.jsx(函数组件)

import React, { useContext } from "react";
import { Button } from 'antd';
import ThemeContext from "../ThemeContext";

//函数组件用store示例

const VoteFooter = function VoteFooter() {
    const { store } = useContext(ThemeContext);

    return <div className="footer">
        <Button type="primary"
            onClick={() => {
                store.dispatch({
                    type: 'VOTE_SUP',
                    stpe:10,
                });
            }}>
            支持
        </Button>

        <Button type="primary" danger
            onClick={() => {
               store.dispatch({
                    type:'VOTE_OPP',
               })
            }}>
            反对
        </Button>
    </div>;
};
export default VoteFooter;


VoteMain.jsx(类组件)

import React from "react";
import ThemeContext from "../ThemeContext";

//类组件用store示例
// store.subscribe接收一个方法---这个方法要能让组件更新的放在事件池当中

class VoteMain extends React.Component {
    static contextType = ThemeContext;

    render() {
        const { store } = this.context; //上下文信息存在this.context
        let { supNum, oppNum } = store.getState();
        let ratio = '--',
            total = supNum+oppNum;
        if(total>0) ratio = (supNum / total *100).toFixed(2) + '%';

        return <div className="main">
            <p>支持人数:{supNum}人</p>
            <p>反对人数:{oppNum}人</p>
            <p>比率:{ratio}</p>
        </div>;
    }

    //类组件第一次渲染完
    componentDidMount() {
        const { store } = this.context;
        store.subscribe(() => {
            this.forceUpdate(); //这个方法的执行 能类组件更新---强制更新
        });
    }
}

export default VoteMain;

手写实现redux的部分源码

自己手写redux部分源码(参考路径:node_modules/redux/dist/reduxs.js/130行)

import _ from './assets/utils';

/* 实现redux的部分源码 */
//源码路径node_modules/redux/dist/reduxs.js/130行
export const createStore = function createStore(reducer) {
    if (typeof reducer !== 'function') throw new Error("Expected the root reducer to be a function");

    let state, //存放公共状态
        listeners = []; //事件池

    /* 获取公共状态 */
    const getState = function getState() {
        // 返回公共状态信息即可
        return state;
    };

    /* 向事件池中加入让组件更新的方法 */
    const subscribe = function subscribe(listener) {
        // 规则校验
        // 1.必须是个函数
        // 2.去重处理,看传进来的是否在事件池中,不在的话再加入事件池includes判断
        if (typeof listener !== "function") throw new TypeError("Expected the listener to be a function");
        // 把传入的方法(让组件更新的办法)加入到事件池中「需要做去重处理」
        if (!listeners.includes(listener)) {
            listeners.push(listener);
        }
        // 返回一个从事件池中移除方法的函数
        return function unsubscribe() {
            let index = listeners.indexOf(listener); //获取它的索引
            listeners.splice(index, 1); //从当前索引位置 删除一项
        };
    };

    /* 派发任务通知REDUCER执行 */
    const dispatch = function dispatch(action) {
        // 规则校验
        if (!_.isPlainObject(action)) throw new TypeError("Actions must be plain objects");
        if (typeof action.type === "undefined") throw new TypeError("Actions may not have an undefined 'type' property");

        // 把reducer执行,传递:公共状态、行为对象;接收执行的返回值,替换公共状态;
        state = reducer(state, action);

        // 当状态更改,我们还需要把事件池中的方法执行
        listeners.forEach(listener => {
            listener();
        });

        return action;
    };

    /* redux内部会默认进行一次dispatch派发,目的:给公共容器中的状态赋值初始值 */
    const randomString = () => Math.random().toString(36).substring(7).split('').join('.');
    dispatch({
        // type: Symbol() //ES6语法 Symbol()唯一值
        type: "@@redux/INIT" + randomString()
    });

    // 返回创建的STORE对象
    return {
        getState,
        subscribe,
        dispatch
    };
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值