Redux使用的基本思路
最近刚学习 Redux,这里分享一下自己对此的理解,如有错误,敬请各位指出,谢谢。
## 基础概念 ##
1、Redux是一个数据层的框架(framework)
2、学习Redux需要理解以下概念:MVC(Model View Controller)、Store、State、Action、dispatch()、Reducer
以下个人对上述概念的理解 参考阮大大的文章 原文地址:Redux 入门教程(一):基本用法
Store
store(商店、仓库、库) 即是保存数据的地方
PS:整个应用只能有一个Store
创建store
Redux提供 creatStore 函数来生成 Store。
示例:
// 引入redux
import { createStore } from 'redux';
//创建Store 需要传递一个函数fn 这里的fn是之后会提及的reducers
const store = createStore(fn);
State
state(状态、某个时刻的数据即是Store的状态)
获取状态的方法是store.getState()
Action
Action(行为、描述数据的行为,“Action 就是 View 发出的通知,表示 State 应该要发生变化了。”)
获取状态的方法是store.getState()
PS:Action是一个对象,它有一个不可缺的属性type
示例:
// type 属性必须,其它属性可自由添加
const action = {
type: 'addTodo',
text: 'HTML',
_id: store.getState()._id
}
从以上示例可以看出Action还可以携带其他信息(数据),也就是说,我们可以使用Action来改变State的值,从而将我们需要的数据通过Action“运输”到 Store;
实际项目中往往会需要多个Action,我们可以通过函数的形式来生成Action对象,我们把这个函数命名为 Action Creator
示例:
const ADD_TODO = 'ADD_TODO';
function addTodo(text, _id) {
return {
type: ADD_TODO,
text,
_id
}
}
const action = addTodo('JavaScript', '007');
dispatch()
dispatch() 用来发送Action的唯一方法
示例:
// 引入 redux createStore
import { createStore } from 'redux';
const store = createStore(fn);
store.dispatch({
type: 'ADD_TODO',
text: 'HTML',
_id:'007'
});
结合Action Creator 以上代码可改写成:
store.dispatch(addTodo('HTML', '007'));
从上面例子可以看出,dispatch(action)接受一个action对象为参数,并将它发送出去,Store接受Action,接受之后需要返回一个新的State(状态)。
Reducer
Reducer(处理器)
dispatch()将 action 发送出来,Store接受这个 action 并返回一个新的状态,此时创建新状态的过程就是Reduer(处理器)
Reducer是一个函数,它接受两个参数 state(当前状态值) && action,返回一个新的状态值 state。
示例:
// state 可以设置默认值
const reducer = function (state = [], action) {
// ...
return new_state;
};
redux 还提供了combineReducers()方法,该方法可混合多个处理器
示例:
// 引入 combineReducers createStore
import { combineReducers, createStore } from 'redux';
function todoList(state = [], action) {
//...
return new_state;
}
function showType(state = 'all',action) {
//..
return new_state
}
//redux 混合处理器
const reducers = combineReducers({
todoList,
showType,
});
var store = createStore(reducers);
Redux使用的基本思路
1) 定义actions.js,其中包括actions type(字符串常量)、Actions creators(返回一个json对象的函数,返回的这个json对象就是actions)
2) 定义reducers.js,包含多个reducer:(state = defaultState, action)=>{……return new_state};最后通过 combineReducers() 将多个reducer整合到一起
3) 创建 store, const store = createStore(Reducers)
4) 在入口文件中render(<组件> , rootElement);
5) React最外层组件中,在事件的回调函数中dispatch(actions creators(data));通过export default connect(select)(App) 绑定Redux与React
暂时这么多,后续会补充和改错。