redux
Redux 理解
Redux 设计之初是为了更好的维护 Web 状态,React 框架实现了 State。React + Redux
Redux 设计的核心是 store 的概念。store 将 State/Action/Reducer 联系在一起。redux 中有且只有一个 store,store 是唯一的
Action 是负责把数据从应用传到 Store 的载体,是 Store 数据的唯一来源,通过 store 的 dispatch() 方法实现
Reducer 将 State 的变化和相应的 Action 发送到 store,然后返回新的 state 给 store
Reducer 本质上一个纯函数,接收 state and action,执行相应操作后,返回新的 state。但切忌做以下操作:
- 修改传入参数;
- 执行有副作用的操作,如请求 API 和 路由跳转等;
- 调用非纯函数,如 Date.now()、Math.random() 等不确定值操作
Redux 负责状态管理、React 负责视图渲染,Redux 中 store 是核心对象,在管理 Reducer 与 State 的同时,还要处理 Dispath 存入的 Action,最终订阅 React 视图更新。
- Redux 其实是一个
JavaScript 状态容器
,可预测状态管理- Redux 并不属于 React 框架,完全独立。可与大多数前端框架完美结合
- /**
- reducer(state, action){}
- state 状态,action 用户操作 action.type 用户操作类型
- store 通过 Redux.createStore(reducer)
- store.subscribe(render) 实现用户订阅功能,当状态发生变化时,自动渲染视图 render 通过 innerHTML 实现
- 操作不同,dispatch 触发不同的 action {type: ‘ACTIONTYPE’}
demo
1 | <script type="text/babel"> |
React-Redux 中的 Provider 容器组件
传递参数多的时采用 React-Redux 库的 Provider 组件容器解决,传递太多参数造成的性能问题,同时还提供了一个 connect 方法来连接与 Store 对象
Provider 组件将 Store 对象包装在顶层容器中,就可以被其子组件继承。
哈哈,请问你是要闹哪样?import { connect } from '@tarojs/redux';
redux 文档里查了没找着,原来是 tarojs 的方法,借机认识下这哥们。
connect
tarojs/redux 提供的 connect 方法将 redux 与我们的页面进行连接
connect 方法接受两个参数mapStateToProps
与mapDispatchToProps
- mapStateToProps,函数类型,接受最新的 state 作为参数,用于将 state 映射到组件的 props
- mapDispatchToProps,函数类型,接收 dispatch() 方法并返回期望注入到展示组件的 props 中的回调方法
Demo
1 | import { connect } from '@tarojs/redux'; |