Redux状态管理器

一个固定的输入,必然会得到一个固定的输出结果

 Redux JavaScript 状态管理库, 提供可预测的状态管理。

 什么时候用redux?

  • 多个组件需要共享同一个状态,各组件可以随时拿到同一个状态的时候
  • 一个组件需要改变另一个组件的状态

遵循三大原则

一,单一数据源

整个应用state被存储在一棵object tree中,并且整个对象树只存在于唯一一个store中

 二,state是只读的

唯一改变state的方法就是触发action

三,使用纯函数来执行修改 

reducer只做一件事情,通过之前的state和当前的action计算得出新的state;

相同的输入必须得到相同的输出结果,因此reducer必须是一个纯函数;

reducer中不应该写有副作用的代码,比如定时器,ajax,获取时间对象与随机数。 

 使用

在src下创建store

 

 

因为代码量会比较庞大,所以将逻辑代码分出去写在reducer文件中。


var initialState = {
    count:0
}

//纯函数
//参数一: state , 之前的state状态
//参数二: action , 触发的action动作
var reducer = ( state = initialState, action:any )=>{
    //深拷贝state
    // var newstate = Object.assign({},state);
    var newstate = JSON.parse( JSON.stringify(state) );

    if( action.type == 'ADD' ){//这里什么类型执行什么代码,由程序员决定。
        newstate.count += action.payload;
        return newstate;//返回全新的state
    }
    else if( action.type == 'SUB' ){
        newstate.count -= action.payload;
        return newstate;//返回全新的state
    }else{
        return state; //走到这里说明只是查看,返回旧的state( 之前的state )
    }

}


export default reducer;

 也可以换一种写法(看个人喜好)


var initialState = {
    count:0
}

//纯函数
//参数一: state , 之前的state状态
//参数二: action , 触发的action动作
var reducer = ( state = initialState, action:any )=>{
    //深拷贝state
    var newstate = JSON.parse( JSON.stringify(state) );

     switch(action.type){
         case 'ADD':
             newstate.count += action.payload;
             return newstate;//返回全新的state
         case 'SUB':
             newstate.count -= action.payload;
             return newstate;//返回全新的state
         default :
             return state; //返回旧的state( 之前的state )
     }
}


export default reducer;

 在组件中,

getState()获取store中的数据

dispatch()触发action修改store中的数据

subscribe()监听store中的数据变化,会返回一个函数,这个函数就是取消监听的方法

import React, { Component } from 'react';
import store from '../../../store'
class Gwc extends Component {
    unsubscribe:any = 0;
    componentDidMount() {
        //监听store中的数据的变化
        this.unsubscribe = store.subscribe(()=>{
            this.setState({});
            console.log('Gwc 监听回调');
        })
    }
    componentWillUnmount() {
        //取消监听
        this.unsubscribe();
    }
    handleClick(){
        //触发action, 修改redux中的数据
        // store.dispatch( { type:'ADD', payload:5 } );
        store.dispatch( { type:'SUB', payload:5 } );
    }
    render() {
        console.log( store.getState() );
        return (
            <div className='gwc'>
                <button onClick={()=>{ this.handleClick() }}>添加</button>
            </div>
        );
    }
}

export default Gwc;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

她比亚索还快乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值