Redux是一个专注于状态管理的库,和React是解耦的,用Angular和Vue都可以使用Redux。其具有一个单一状态,单向数据流的特性。
Redux概念
redux有一个store,记录所有的state,state要改变的时候,就通知dispatch去执行action,reducer拿到state和action去生成新的state,store.subscribe根据新的state重新渲染出改变后的样式。Redux使用:
1、通过reducer新建store;
2、我们可以通过store.getState获取状态;
3、状态要变更的时候,store.dispatch(action)来修改状态;
4、reducer函数接受state和action,返回新的state;
5、可以用store.subscribe监听每次修改并自动执行重新渲染的动作。
感觉还是很抽象,我们通过写代码来理解看看。
1、create-react-app创建项目,再npm run eject一下,方便后面自定义配置。
2、安装redux:
npm install redux --save
3、清空index.js文件,先引入redux的createStore方法:
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'
})