14React Redux入门

官网:https://redux.js.org/
安装:

npm install redux --save

demo案例:

// redux的使用
import {createStore} from "redux";
// 初始化的时候执行一次 更新数据的时候执行一次
// 第二参数action会接受dispath中传来的type值
const store = createStore( (state = {count: 0}, action) => {
    switch(action.type) {
        case "INCREMENT": 
            return {
                count: state.count + 1
            }
        case "DECREMENT": 
            const decrementBy = typeof action.decrementBy === "number" ? action.decrementBy : null;
            if(decrementBy) {
                return {
                    count: state.count - decrementBy
                }
            }else {
                return {
                    count: state.count - 1
                }
            }
        // 归零
        case "RESET": 
            return {
                count: state.count = 0
            }
        // 设置
        case "SET": {
            return {
                count: action.count
            }
        }
        default: 
            return state;
    }
    // if(action.type === "INCREMENT") {
    //     return {
    //         count: state.count + 1
    //     }
    // }else{
    //     return state;
    // }
    
});
// 获取数据
// console.log(store.getState())
// 订阅
store.subscribe(() => {
    console.log(store.getState())
})
// dispatch也会执行一次createStore函数
store.dispatch({
    type: "DECREMENT",
    decrementBy: 10
})
store.dispatch({
    type: "DECREMENT"
})
store.dispatch({
    type: "DECREMENT"
})
// 获取数据
console.log(store.getState())
store.dispatch({
    type: "RESET"
})
// 获取数据
// console.log(store.getState())
store.dispatch({
    type: "SET",
    count: 1000
})

在这里插入图片描述
几个实用的方法:
store.getState() 获取数据
store.subscribe() 订阅推送
store.dispatch() 操作或更新数据和传值

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值