React从入门到放弃之前奏(3):Redux简介
安装
npm i -S redux react-redux redux-devtools
概念
在redux中分为3个对象:Action、Reducer、Store
Action
- 对行为(如用户行为)的抽象
- Action 就是一个普通 JavaScript 对象。如:
{ type: 'ADD_TODO', text: 'Go to swimming pool' }(其中type字段是约定也是必须的) - 作为Reducer的参数
Reducer
- 一个普通的函数,用来修改store的状态。
- 函数签名:
(currentState,action)=>newState- 在 default 情况下返回currentState
Object.assign({},state, { visibilityFilter: action.filter })(第一个参数不能为state) 等价于ES7的{ ...state, ...newState }
- redux 的 combineReducers 方法可合并reducer
Store
- 代表数据模型,内部维护了一个state变量
- 两个核心方法,分别是getState、dispatch。前者用来获取store的状态(state),后者用来修改store的状态
- createStore(reducer) 可创建Store
redux示例:
import { createStore } from 'redux'
// reducer
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
default:
return state
}
}
// state
let store = createStore(counter); // 会调用
// 监听
store.subscribe(() =>
console.log(store.getState())
);
// 调用reducer
store.dispatch({ type: 'INCREMENT' });
react-redux
react的需求:
- 数据总是单向从顶层向下分发的
- 组件之间的沟通通过提升state:子组件改变父组件state的办法只能是通过onClick触发父组件声明好的回调
- state越来越复杂:单页应用的发展导致。包括服务器响应、缓存数据、本地生成尚未持久化到服务器的数据,也包括 UI 状态,如激活的路由,被选中的标签,是否显示加载动效或者分页器等等。
react-redux 将react组件分为2种:展示组件 和 容器组件
展示组件
描述如何展示:负责UI样式的展示
- 数据来源:props
- 数据修改:通过props的回调函数
- 不直接使用redux
容器组件
描述如何运行:负责数据获取 和 状态更新
- 数据来源:redux state
- 数据修改:redux 派发action
- 直接使用redux
react-redux 只有2个API:Provider 和 connect
Provider
<Provider store>
- 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
- 接收Redux的store作为props,内部通过context对象传递给子孙组件上的connect
connect
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])(Component)
作用:连接React组件与 Redux store
mapStateToProps(state, ownProps) : stateProps:
- 将 store 中的数据作为 props 绑定到组件上。
- 当 state 变化,或者 ownProps 变化的时候,mapStateToProps 都会被调用,计算出一个新的 stateProps
mapDispatchToProps(dispatch, ownProps): dispatchProps:将 dispatch(action) 作为 props 绑定到组件上
mergeProps:指定 stateProps 以及 dispatchProps 合并到 ownProps 的方式。(默认使用Object.assign)
connect是个高阶组件(HOC)大致源码:
export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
return function wrapWithConnect(WrappedComponent) {
class Connect extends Component {
constructor(props, context) {
this.store = props.store || context.store
this.stateProps = computeStateProps(this.store, props)
this.dispatchProps = computeDispatchProps(this.store, props)
this.state = { storeState: null }
// 合并stateProps、dispatchProps、parentProps
this.updateState()
}
shouldComponentUpdate(nextProps, nextState) {
// 进行判断,当数据发生改变时,Component重新渲染
if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
this.updateState(nextProps)
return true
}
}
componentDidMount() {
this.store.subscribe( () => this.setState({ storeState: this.store.getState() }) )
}
render() {
return (
<WrappedComponent {...this.nextState} />
)
}
}
return Connect;
}
}
react-redux示例:
Counter.js
import React, { Component } from 'react';
import { createStore, bindActionCreators } from 'redux';
import { Provider, connect } from 'react-redux';
function clickReduce(state = { todo: 1 }, action) {
switch (action.type) {
case 'click':
return Object.assign({}, state, { todo: state.todo + 1 });
default:
return state;
}
}
let store = createStore(clickReduce);
class Counter extends Component {
render() {
return (
<div>
<div>{this.props.todo}</div>
<button onClick={this.props.clickTodo}>Click</button>
</div>
)
}
}
// 方式1:
export default connect(state => ({ todo: state.todo }),
dispatch => ({ clickTodo: () => dispatch({ type: 'click' }) }))(Counter)
// 方式2:
export default connect(state => ({ todo: state.todo }),
dispatch => bindActionCreators({ clickTodo: () => ({ type: 'click' }) }, dispatch))(Counter);
index.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import Clock from './Clock'
render((
<Provider store={store}>
<Counter />
</Provider>), root);
在redux中,我们只能dispatch简单的action对象。
对应的在react-redux中,我们只能定义同步的reducer方法。
下节将介绍在react-redux如何定义异步方法。让其更加适用于生产环境。
React从入门到放弃之前奏(3):Redux简介的更多相关文章
- React从入门到放弃之前奏(5):ReactRouter4
概念 安装:npm i -S react-router react-router-dom GitHub:ReactTraining/react-router React Router中有三种类型的组件 ...
- React从入门到放弃之前奏(1):webpack4简介
接触webpack是好久之前的事情了,最近看了下webpack没想到都到4了. webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler). 会创建1个 ...
- React从入门到放弃之前奏(2):React简介
本系列将尽可能使用ES6(ES2015)语法.所以均在上节webpack的基础上做开发. React是Facebook开发的一款JS库,因为基于Virtual DOM,所以响应速度快,以及支持跨平台. ...
- React从入门到放弃之前奏(4):Redux中间件
redux 提供了类似后端 Express 的中间件概念. 最适合扩展的是redux中的 store.dispatch 方法,中间件实际就是通过 override redux的store.dispat ...
- 在 2016 年学 JavaScript 是一种什么样的体验?(React从入门到放弃)
jquery 年代 vs 前端模块化 http://blog.csdn.net/offbye/article/details/52793921 ++ 嘿,我最近接到一个 Web 项目,不过老实说,我这 ...
- ubuntu-docker入门到放弃(七)Dockerfile简介
一.dockerfile基本结构 最简单的理解就是dockerfile实际上是一些命令的堆叠,有点像最基础的shell脚本,没有if 没有for,就是串行的一堆命令. 一般而言,dockerfile分 ...
- D3.js从入门到“放弃”指南
前言 近期略有点诸事不顺,趁略有闲余之时,玩起D3.js.之前实际项目中主要是用各种chart如hightchart.echarts等,这些图形库玩起来貌都是完美的,一切皆可配置,但几年前接触了D3之 ...
- 一天带你入门到放弃vue.js(一)
写在前面的话! 每个新的框架入手都会进行一些列的扯犊子!这里不多说那么多!简简单单说一下vue吧! Vue.js是目前三大框架(angular,vue,react)之一,是渐进式js框架,据说是摒弃了 ...
- 小白学 Python 爬虫(28):自动化测试框架 Selenium 从入门到放弃(下)
人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...
随机推荐
- Java语言实现二分法
二分法是一个简单,高效,并广泛应用的查找方法 import java.util.arrays; public class BinarySearch { public static int rank(i ...
- SharePoint2007 开发部署Application Pages
介绍:SharePoint应用程序页,也就是_layouts路径下的aspx页面,服务器C:\Program Files\Common Files\Microsoft Shared\web serve ...
- 从ruby实现时间服务器ntp同步功能也谈“逆向工程”
本猫以前写asm和C的时候常常不忘"逆向"一把,后来写驱动的时候也用VM之类的搭建"双机"调试环境进行调试:也对于一些小的软件crack cd-key神马的不亦 ...
- reorder list(链表重新排序)
Given a singly linked list L: L0→L1→-→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→- You must do thi ...
- Google高级搜索技巧十则
前言:多数人在使用Google搜索的过程是非常低效和无谓的,如果你只是输入几个关键词,然后按搜索按钮,你将是那些无法得到Google全部信息的用户,在这篇文章中,Google搜索专家迈克尔.米勒将向您 ...
- Struts2,Spring,Hibernate优缺点
struts框架具有组件的模块化,灵活性和重用性的优点,同时简化了基于MVC的web应用程序的开发. 优点: Struts跟Tomcat.Turbine等诸多Apache项目一样,是开源软件,这是它的 ...
- 通过slave_exec_mode=IDEMPOTENT跳过主从复制中的错误
通过slave_exec_mode=IDEMPOTENT跳过主从复制中的错误 set global slave_exec_mode=IDEMPOTENT slave_exec_mode 有两种模式 S ...
- truffle 安装以及基本指令
1. linux下安装方式 $ npm install -g truffle 环境要求: NodeJS 5.0+ Windows,Linux,或Mac OS X 2. 创建工程: $ mkdir te ...
- Activex、OLE、COM、OCX、DLL之间有什么区别?
来源:http://www.blogjava.net/Jack2007/archive/2008/04/27/196392.html 熟悉面向对象编程和网络编程的人一定对ActiveX ...
- es6(三):es6中函数的扩展(参数默认值、rest参数、箭头函数)
1.函数可以设置参数默认值 function test1(x,y=1){ console.log(x,y) } test1(10)//10 1 2.rest参数:形式为...变量名 function ...