redux 入门之 store 状态机

发布于 2022-05-08 10:09:52 字数 1674 浏览 1264 评论 0

store 是什么?

store 是一个管理 state 的大对象,并且提供了一系列的方法

getState(),  // 返回 state
dispatch(action),  // 派发一个 action
subscribe()  // 订阅监听

通过 redux 提供的 createStore,传入 reducer 函数,我们可以得到一个 store 对象

import { createStore } from 'redux'
const store = createStore(reducer)

简单实现一个 createstore 函数

// 这是一个工厂函数,可以创建 store
const  createStore = (reducer) => {
   let state; // 定义存储的state
   let listeners = [];
   
  //  getState的作用很简单就是返回当前是state
  const  getState = ()=> state;
  
    //定义一个派发函数
    //当在外界调用此函数的时候,会修改状态
  const dispatch = (action)=>{
      //调用reducer函数修改状态,返回一新的状态并赋值给这个局部状态变量
      state = reducer(state,action);
      //依次调用监听函数,通知所有的监听函数
      listeners.forEach(listener => listener());
  }
   //订阅此状态的函数,当状态发生变化的时候记得调用此监听函数
  const subscribe = function(listener){
      //先把此监听 加到数组中
      listeners.push(listener);
      
      //返回一个函数,当调用它的时候将此监听函数从监听数组移除
      return function(){
          listeners = listeners.filter(l => l != listener);
      }
  }
    //默认调用一次dispatch给state赋一个初始值
   dispatch({types: 'INIT'});
  return {
      getState,
      dispatch,
      subscribe
  }
}

使用

function numReducer (state = 0, action) {
  switch (action.types) {
    case 'increase':
      return state + 1
      break;
    case 'deincrease':
      return state - 1
    default:
      return state
  }
}
let store = createStore(numReducer);
store.subscribe(() => {
  console.log('触发了')
})
store.dispatch({types: 'increase'})
console.log(store.getState())
// 触发了 1

注意的点

根据官方的说法,一个应用应该只有一个 store,即单一数据源,我们通过合并 reducer 来壮大 state tree

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

内心荒芜

暂无简介

0 文章
0 评论
23 人气
更多

推荐作者

lioqio

文章 0 评论 0

Single

文章 0 评论 0

禾厶谷欠

文章 0 评论 0

alipaysp_2zg8elfGgC

文章 0 评论 0

qq_N6d4X7

文章 0 评论 0

放低过去

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文