Redux 是什么

每当咱们谈及到 redux,你们都会说是 react 的状态管理工具。这么说确实没错,毕竟 redux 项目也是 React Community 组织下的一个子项目。并且 redux 的诞生也是和 react 这个 ui 库急需一个状态管理解决方案有很大的联系。可是 redux 和 react 并无任何的耦合。虽然它们常常一块儿用,可是 redux 的用途并不局限于 react,或者说,和 react 的结合只是 redux 的使用方式之一。node

那么撇开 react 不谈, redux 究竟是什么呢?咱们看一下这个例子。react

在实际的开发当中,咱们可能会碰到这样的需求:监听一个事件,当事件触发的时候,咱们能够作一些想作的事情。git

const cat = {
  name: 'youtiao',
  age: 1,
  weight: 6
};

// 监听 'update_weight' 事件
events.on('update_weight', weight => {
  if (weight > cat.weight) {

    // 没错,要作的事情就是无情的嘲讽
    console.log('哈哈哈,你又长胖了!!');
    cat.weight = weight;
  }
});

// 触发 'update_weight' 事件
events.trigger('update_weight', { weight: 8 });

// 查看改变以后的 cat
console.log(cat);
复制代码

开源社区有不少库能够完成这样的需求,固然,这里是讲 redux 的,按照剧本走,咱们确定用 redux 来作啦。github

const { createStore } = require('redux');

// 监听事件
const listener = (oldCat, action) => {

  // 注册 'update_weight' 事件
  if (action.type === 'update_weight') {
    
    // 当新的 weight 大于旧的 weight 时
    if (action.weight > oldCat.weight) {
      console.log('哈哈哈,你又长胖了!!');
      const newCat = Object.assign({}, oldCat, { weight: action.weight });
      return newCat;
    }
  }
  return oldCat;
};

// 绑定监听事件到 cat 对象上
const store = createStore(listener, cat);

// 触发 'update_weight' 事件
store.dispatch({ type: 'update_weight', weight: 8 });

// 查看触发事件以后的 cat 对象
console.log(store.getState());
// 哈哈哈,你又长胖了!!
// { name: 'youtiao', age: 1, weight: 8 }
复制代码

可是!!!redux 是一门很讲究的库,虽然上面的例子跑起来没有任何问题,可是有一件事情 -- 嘲讽console.log('哈哈哈,你又长胖了!!'),不该该放在 listener 里面作。而是应该放到 redux 中间件里去作。至于什么是 redux 中间件为何要这么麻烦,我以为能够在后面的文章中再和你们探讨一下,同时也欢迎你们在评论区提出本身的意见和建议。redux

好,看完这个例子,你们知道 redux 是什么了吗?emmm,其实我也不知道 redux 是什么,反正我知道了它能够用来作什么事情。就像一个扳手🔧,它创造出来是用来拧螺丝的,也许这是它最擅长的。可是谁说不能用扳手来砸核桃呢,或者当装饰,甚至当武器也能够呀~工具

代码地址: Redux 是什么,直接控制台运行 node ./demo0/index.js 查看效果post

下一篇:Redux 入门 -- 基础用法ui

相关文章
相关标签/搜索