React中状态管理之redux、react-redux、mobx简单总结

Redux

一、什么是redux:

Redux 是 JavaScript 状态容器,提供可预测化的状态管理。可以让你构建一致化的应用,运行于不同的环境(客户端、服务器、原生应用),并且易于测试。Redux 除了和 React 一起用外,还支持其它界面库。 它体小精悍(只有2kB,包括依赖)。

二、安装与引入:

npm install --save redux //安装

import { createStore } from 'redux' //引入

三、redux三大原则:

单一数据源、state是只读的,使用纯函数来执行修改。

四、使用redux:

当安装好redux包并引入以后,我们通过creteStore(reducer)创建一个store状态机,用于状态管理。

reducer是一个纯函数【纯函数即返回值只有传入的参数决定】,reducer(state,action)有2个参数,state为当前的状态,action 就是一个描述“发生了什么”的普通对象,reducer中通过switch流程控制语句判断action.type的值,来更改state。

通过使用store.dispatch(action)来触发aciton的改变,然后通过store.subscribe(()=>{}),来手动订阅更新,当store.dispatch(action)后,就会触发store.subscribe。通过使用store.getState()获取当前store中state状态。

1、State:

1.1、DomainState:服务端返回的State;
1.2、UI State:关于当前组件的State;
1.3、App State:全局的State;

2、Action事件:

2.1、本质就是一个JS对象;
2.2、必须包含type属性;
2.3、只是描述了有事情要发生,并没有描述如何去更新State;

3、 Reducer:

3.1、本质就是函数;
3.2、响应发送过来的Action;
3.3、函数接收两个参数,第一个是初始化State,另一个是发送过来的Action;
3.4、必须要有return返回值;

4、Store:

Store就是把action与reducer联系到一起的对象。
主要职责:
4.1、维持应用的state;
4.2、提供getState()方法获取state;
4.3、提供dispatch()方法发送action;
4.4、通过subscribe()方法注册监听;
4.5、通过subscribe()返回值注销监听。

Import {createStore} from ‘redux’

const store = createStore(传递的reducer)

五、使用:

项目结构如下:

1、创建一个Action:

1.1、在根目录下创建一个文件夹action,在action下创建一个index.js文件用来构建Action:
const sendAction = () => {...} ;
1.2、在action创建函数里面利用return返回一个action对象,注意要携带type属性:
const sendAction  = () => {return {type: ‘send_action’, value: ‘发送了一个action’}}
1.3、把这个action创建函数进行导出:

module.exports = { sendAction }

代码:

const sendAction = () => {
    return {
        type: 'send_type',
        value: '这是一个action'
    }
}

module.exports = {
    sendAction
}

2、创建一个Reducer:

2.1、在根目录下创建一个reducer目录,在reducer目录下创建一个index.js文件用来构建reducer,注意reducer要有两个接收函数:

const rootReducer = (state,  action) => {...} 

2.2、第一个参数是默认状态,我们可以定义一个初始化的state,然后进行赋值:

const initState = {value: ‘默认值’}
const rootReducer = (state=initState ,  action) => {...} 

2.3、在函数里面判断第二个参数action的type值是否是我们需要发送的,如果是的话我们可以通过return返回新的state;
2.4、把reducer进行导出;

代码:

const initState = {
    value: "默认值"
}

const reducer = (state = initState, action) => {
    switch(action.type){
        case "send_type":
            return Object.assign({}, state, action) ;
        default: 
            return state;
    }
}

module.exports = {
    reducer
}

3、构建Store:

3.1、在根目录下创建store文件夹,在store文件夹下创建index.js文件来构建store,注意createStore函数里面第一个参数是reducer:

import {createStore} from ‘redux’
// 在此导入创建的reducer
const store  =  createStore(reducer)

3.2、createStore返回值就是我们创建的store;
3.3、将创建的store进行导出;

代码:

import {createStore} from 'redux'
import {reducer} from '../reducer'

const store = createStore(reducer);

export default store;

4、在组件中使用:

4.1、给组件ButtonCom.js中的button按钮绑定一个点击事件;
4.2、在组件一加载完毕的时候我们通过store来进行监听器的注册,返回值可以用来注销监听:

this.unSubscribe = store.subscribe(()=>{...})

4.3、在点击事件函数处理中通过store.dispatch来发送一个action:

handle = () => {
store.dispatch(sendAction());
}

代码:

import React from 'react'
import { Button } from 'antd';
import { RedoOutlined } from '@ant-design/icons';
import store from './store'
import {sendAction} from './action'

export default class MenuCom extends React.Component {
    /*constructor(props) {
        super(props);
        //subscribe当store中数据发生变化就会更新数据
        store.subscribe(function () {
            this.setState({
                storeValue: store.getState()
            })
        })
    }*/

    state = {
        storeValue: store.getState()
    }

    onSubscribe = () => {
        this.setState({
            storeValue: store.getState()
        })
    }

    componentWillMount = () => {
        store.subscribe(this.onSubscribe)
    }

    handleClick = ()=>{
        const action = sendAction();
        store.dispatch(action);
    }

    render() {
        return (<>
            <Button type="primary" icon={<RedoOutlined/>} ghost onClick={()=>this.handleClick()}>修改</Button>
            <div>{store.getState().value}</div>
        </>)
    }
}

再看一个简单的实例:

import React, { Component } from 'react'
import { Button } from 'antd'
import { createStore } from 'redux'

const reducer = (state = { value: 0 }, action) => {
    switch (action.type) {
        case "add":
            return Object.assign({}, { value: ++state.value });
        case "power":
            return Object.assign({}, { value: state.value * state.value });
        default:
            return state;
    }
}

const store = createStore(reducer);
export default class Bar extends Component {
    constructor(props) {
        super(props);
        store.subscribe(this.onDispatch);
    }

    state = {
        storeValue: store.getState()
    }

    onDispatch = () => {
        this.setState({
            storeValue: store.getState()
        })
    }

    onAdd = () => {
        store.dispatch({ type: "add" });
    }

    onPower = () => {
        store.dispatch({ type: "power" });
    }

    render() {
        return (
            <div>
                <p>{this.state.storeValue.value}</p>
                <p><Button type="primary" onClick={() => this.onAdd()}>Add</Button></p>
                <p><Button type="primary" onClick={() => this.onPower()}>Power</Button></p>
            </div>
        )
    }
}

六、总结:

完整示例:https://github.com/samveduan/redux.git

react-redux

完整示例:https://github.com/samveduan/react-redux.git

Mobx:

Mobx的使用方法:https://blog.csdn.net/duansamve/article/details/116749220

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值