Redux单独在HTML中的用法

引入redux.js:

https://cdn.bootcdn.net/ajax/libs/redux/4.2.0/redux.min.js

第一步:定义 reducer函数 作用:根据定义的数据状态修改之后返回新的状态

function reducer(state = {count: 0}, action) {
        if (action.type === "ADD") {
            state.count = state.count + 1;
            return state
        }

        if (action.type === "REDUCE") {
            state.count = state.count - 1
            return state
        }

        return state
    }

第二步:通过createStore方法,创建store 实例对象

  const store = Redux.createStore(reducer);
    console.log(store);

第三步:订阅实例store的subscribe方法

  store.subscribe(() => {
        document.getElementById("count").innerHTML = store.getState().count;
    })

第四步:触发实例store 的 dispatch方法 提交Action

  store.dispatch({
                type: "REDUCE"
            })

//第五步:通过实例store的getState方法获取最新的数据状态

store.getState().count;

完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Redux</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/redux/4.2.0/redux.min.js"></script>

</head>
<body>
<button id="reduction">-</button>
<button id="count">0</button>
<button id="add">+</button>


<script>

    //第一步:定义 reducer函数 作用:根据定义的数据状态修改之后返回新的状态
    function reducer(state = {count: 0}, action) {
        if (action.type === "ADD") {
            state.count = state.count + 1;
            return state
        }

        if (action.type === "REDUCE") {
            state.count = state.count - 1
            return state
        }

        return state
    }

    //第二步:通过createStore方法,创建store 实例对象
    const store = Redux.createStore(reducer);
    console.log(store);


    //第三步:订阅实例store的subscribe方法
    store.subscribe(() => {
        document.getElementById("count").innerHTML = store.getState().count;//第五步:通过实例store的getState方法获取最新的数据状态
    })
    onAdd()
    //添加
    function onAdd() {
        let ele = document.getElementById("add");
        ele.addEventListener('click', () => {
            //第四步:触发实例store 的 dispatch方法 提交Action
            store.dispatch({
                type: "ADD"
            })
        })
    }

    onReduce();

    //减少
    function onReduce() {
        let ele = document.getElementById("reduction");
        ele.addEventListener('click', () => {
            //第四步:触发实例store 的 dispatch方法 提交Action
            store.dispatch({
                type: "REDUCE"
            })
        })
    }


</script>
</body>
</html>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值