Redux 基本概念和使用
先从 Flux 开始
先放一个 Flux 官网 https://Facebook.GitHub.io/flux/ 的链接. 需要 fq.
Flux 是 Facebook 提出的一种构建客户端网页应用的应用架构, 它是一种抽象程度很高的设计模式, 鼓励单向数据流.
在之前的 MVC 架构中, 在小型应用中, Model 和 View 较少时, 关系不复杂, 维护轻松. 但是一旦功能越来越复杂, 将难以维护, 多个 Model 和多个View 之间存在着多对多的关系, 在开发时, 需要花费很多时间去处理 Modal 间的关系.
Flux 架构的关键在于单向数据流, 他由三部分构成 --
- dispatcher
- stores
- views(React components)
从一次 Action 触发, Dispatcher 将它 dispatch 到 store, 更新 store,store 的变化同步更新到对应的 view 层. 等待下一次的 Action 触发.
这个过程中, 数据始终是单向流动的.
社区基于 Flux 有多种实现, 其中 Dan 大神的 Redux 最受推崇, 已经成为事实标准.
Redux
前面的文章提到了组件间通信的几种方式, context API 在小规模共享应用时值得一试. 今天主要讲解 react 全家桶中的 Redux.
概念
在说概念之前, 先看一张图:
| 图片来源 https://CSS-tricks.com/learning-react-redux/
根据上面的图片, 可以发现 Redux 相当于一个全局的 Provider.各个子组件是 Consumer.
当然,Redux 不只是简单的提供一个全局 Provider.
它有以下几个特点:
1.唯一数据源
不同于Flux 的实现,Redux 只有一个唯一的数据源, 它提供一个深层嵌套的对象来存放所有数据.
2. 状态只读
在 Redux 中, 所有的状态都是只读的, 如果要修改 state, 则需要 dispatch 一个 action,reducer 通过 action 的 type, 选择执行不同的操作, 返回新的状态.
3. 通过纯函数改变状态
纯函数的概念很简单, 一个函数, 给定输入, 则确定输出, 不受其他因素影响, 也不会影响原来的引用.
由于 Redux 提倡纯函数对状态进行处理, 不会更改之前的对象, 对于操作
fn(x) = y;
只要 x 给定, 则 y 一定是确认值. 这样不论是之后进行很方便来追踪数据的更改, debug, 时间回溯, 都非常方便.
使用
Redux 的 API 非常简单, 这里是 Redux API 文档 https://cn.redux.JS.org/docs/API/ .
我们只需要使用两个API 就能使用到 Redux.
- // 创建一个 Reducer
- let countReducer = (state = 0, action) => {
- if (action.type === 'ADD') {
- state++;
- }
- return state;
- }
- // 创建一个 Store
- var store = Redux.createStore(countReducer);
- // dispatch 一个 action
- store.dispatch({
- type: 'ADD'
- });
如果有多个State, 比如, count 和 user, 则需要使用 combineReducers 方法.
- import { createStore, combineReducers } from 'redux';
- // The User Reducer
- const userReducer = (state = {}, action) => {
- return state;
- }
- // The Widget Reducer
- const countReducer = (state = {}, action) => {
- return state;
- }
- // Combine Reducers
- const reducers = combineReducers({
- userState: userReducer,
- countState: countState,
- });
- const store = createStore(reducers);
在实际使用时,有 ActionCreateor 的概念, 其实并不复杂, 就是一个函数, 返回响应的 Action. 可以在这个函数中对 Action 做一些逻辑的判断处理.
CountActionCreators.JS
- export function plus() {
- return {
- type: 'PLUS'
- };
- }
- export function minus() {
- return {
- type: 'MINUS'
- };
- }
接下来需要调用bindActionCreators.
- let one = bindActionCreators({
- plusOne, minusOne
- }, store.dispatch);
- store.subscribe(() => console.log(store.getState()));
- one.plusOne();
- one.minusOne();
这里是一个完整的例子 - codesandbox https://7yqw290wrq.codesandbox.io/ .
来源: https://www.cnblogs.com/liuyongjia/p/9775111.html