react学习-redux快速体验

发布于:2024-06-19 ⋅ 阅读:(128) ⋅ 点赞:(0)

1.redux是用于和react搭配使用的状态管理工具,类似于vue的vuex。redux可以不和任何框架绑定,独立使用
2.使用步骤
(1)定义一个reducer函数(根据当前想要做的修改返回一个新的状态)
(2)使用createStore方法传入erducer函数生成一个store实例对象
(3)使用store实例的subscribe方法订阅数据变化(数据一旦变化可以得到通知)
(4)使用store实例的dispatch方法提交action对象 触发数据变化(告诉reducer你想要怎么改数据)
(5)使用store实例的getState方法获取最新的状态数据更新到视图中
3.代码案例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="decrement">-</button>
    <span id="count">0</span>
    <button id="increment">+</button>

    <script src="https://cdn.bootcss.com/redux/4.0.0/redux.js"></script>
    <script>
      // 1.定义reducer函数
      // 作用:根据不同的action对象,返回不同的新的state
      //   state:管理的数据初始状态
      // action:对象type标记当前想要做什么样的修改
      function reducer(state = { count: 0 }, action) {
        // 数据不可变:基于原始状态生成一个新的状态
        if (action.type === "INCREMENT") {
          return { count: state.count + 1 };
        }
        if (action.type === "DECREMENT") {
          return { count: state.count - 1 };
        }
        return state;
      }
      // 2.通过reducer函数生成store实例
      const store = Redux.createStore(reducer);
      // 3.通过store实例的subscribe订阅数据变化
      //   回调函数可以在每次state发生变化时自动执行
      store.subscribe(() => {
        console.log("state变化了");
        document.getElementById("count").innerText = store.getState().count;
      });
      // 4.通过store实例的dispatch函数提交action更改状态
      const inBtn = document.getElementById("increment");
      inBtn.addEventListener("click", () => {
        store.dispatch({
          type: "INCREMENT",
        });
      });
      const dBtn = document.getElementById("decrement");
      dBtn.addEventListener("click", () => {
        store.dispatch({
          type: "DECREMENT",
        });
      });
    </script>
  </body>
</html>


网站公告

今日签到

点亮在社区的每一天
去签到