我爱编程

【React.js 06】Redux基础知识

2018-03-31  本文已影响102人  IUVO

Redux是一个专注于状态管理的库,和React是解耦的,用AngularVue都可以使用Redux。其具有一个单一状态,单向数据流的特性。

感觉还是很抽象,我们通过写代码来理解看看。

1、create-react-app创建项目,再npm run eject一下,方便后面自定义配置。
2、安装redux:

npm install redux --save

3、清空index.js文件,先引入reduxcreateStore方法:

import { createStore } from 'redux'

4、在index.js文件,定义reducer,利用reducer来将旧的state以及传入的action来生成新的state,如下管理公司的例子,manageCompany()就是reducer,其接受的参数为旧的状态state和要执行的方法action,根据方法的类型type,返回新的state

function manageCompany(total = 1, action) {
  switch (action.type) {
    case 'hireEmployee':
      return total + 1;
    case 'fireEmployee':
      return total - 1;
    default:
      return 1;
  }
}

5、通过前面定义的reducer来创建store:

const store = createStore(manageCompany)

6、现在store有了,我们通过store获取一个状态看看:

const opening = store.getState()
console.log(`开业了,公司现在有${opening}人`);
终端显示

7、假设现在公司执行了招聘的动作,那么就要通过dispatch去派发动作:

//派发事件,传递action给reducer
store.dispatch({
  type:'hireEmployee'
})
console.log(`招聘1人,公司现在有${store.getState()}人`);

//派发事件,传递action给reducer
store.dispatch({
  type:'fireEmployee'
})
console.log(`开除1人,公司现在有${store.getState()}人`);
终端显示

8、每次执行事件之后,再来手动打印状态,是不是很麻烦,这也能简化,利用store.subscribe监听每次修改并自动执行打印的事件:

//订阅监听事件
function listener() {
  console.log(`公司现在有${store.getState()}人`);
}
store.subscribe(listener)

这样,每次reducer执行事件后,都会自动调用listener()事件。

这就是Redux的基本使用,这样写和React有什么关系?
没有任何关系!!!这里只是Redux的引入。
下一篇我们再来讲讲Redux怎么用在React上。

附上源码:./src/index.js

import { createStore } from 'redux'

// 定义reducer
function manageCompany(total = 1, action) {
  switch (action.type) {
    case 'hireEmployee':
      return total + 1;
    case 'fireEmployee':
      return total - 1;
    default:
      return 1;
  }
}

//通过reducer创建store
const store = createStore(manageCompany)

//订阅监听事件
function listener() {
  console.log(`公司现在有${store.getState()}人`);
}
store.subscribe(listener)

//初期先获取一次状态看看
const opening = store.getState()
console.log(`开业时公司现在有${opening}人`);

//派发事件,传递action给reducer
store.dispatch({
  type:'hireEmployee'
})

//派发事件,传递action给reducer
store.dispatch({
  type:'fireEmployee'
})

上一篇下一篇

猜你喜欢

热点阅读