通过前面的教程,我们有了简单的环境,并且可以运行Redux的程序,也对 如何编写Redux示例 有了初步的印象;

掌握了 使用Redux控制状态转移 ,继而驱动 React 组件发生改变,这才是学习Redux的初衷。

本篇我们将 Redux 和 React 联合起来,着重讲解redux-react模块的使用;

1、编写红绿灯React组件

在原有的基础上,我们编写红绿灯组件:

touch components/light/index.js components/light/index.less

components/light/index.js 中写React代码,其结构非常简单:

import React, { PropTypes, Component } from 'react'
import { render } from 'react-dom'
import classnames from 'classnames'
import './index.less' class Light extends Component{
render(){
let color = this.props.light.color;
return(
<div className="traffic-light">
<span className={classnames('light',color)} />
</div>
)
}
} Light.propTypes = {
light: PropTypes.object.isRequired
} Light.defaultProps = {
light : {color:'red',time:'4'}
} export default Light

根据更改样式类名('red'、'green'、'yellow'),从而移动 sprite图 产生灯变换的效果:

.traffic-light{
.light{
display: inline-block;
background: url(//lh3.googleusercontent.com/-YWLqWZXDYHU/VmWC7GHoAuI/AAAAAAAACgk/nXvEmSWAhQU/s800/light.png) no-repeat 0 0;
background-size: auto 100%;
overflow: hidden;
width:140px / 2;
height:328px / 2; &.red{
background-position: 0,0;
}
&.yellow{
background-position: -78px , 0;
}
&.green{
background-position: -156px , 0;
}
}
}

修改 components/light/demo.js 文件代码为:

import React, {Component, PropTypes} from 'react'
import {render} from 'react-dom'
import Light from './index' var color = 'red'; render(
<div id="traffic">
<Light color={color}/>
</div>,
document.getElementById('demo')
)

这样就能通过 http://localhost:3000/light/demo 预览这个组件了;

2、链接React和redux

有了React和之前的Redux,现在就要将两者链接起来了。我们的目标是让红绿灯运行起来,就好比平时在十字路口看到的那样;

2.1、创建示例文件

再创建一个示例文件,就不叫demo了,叫做redux好了:

touch components/light/redux.js

之所以示例文件名称为demo.jsredux.js,是因为我在 webpack.config.js 中配置了,如果想用其他的文件名,只要依样画葫芦就可以;

首先在 components/light/redux.js 中输入最基本的脚手架代码,引入所需要的组件或模块:

import React, {Component, PropTypes} from 'react'
import {render} from 'react-dom'
import { Provider, connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as LightActions from '../../actions/light/'
import lightStore from '../../stores/light/'
import Light from './index' // 声明store
let store = lightStore();

2.2、创建容器React

继而创建一个 App React类 ,作为总的容器,将上述的 Light 组件放入其中:

import React, {Component, PropTypes} from 'react'
import {render} from 'react-dom'
import { Provider, connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as LightActions from '../../actions/light/'
import lightStore from '../../stores/light/'
import Light from './index' // 声明store
let store = lightStore(); class App extends Component{
_bind(...methods){
methods.forEach((method)=>this[method] = this[method].bind(this));
}
constructor(){
super();
this._bind('autoChange','handleClick');
this.state = {
count : 0,
timeId : null
}
} autoChange(){ // 自动更改红绿灯
var _self = this; // 这里放置逻辑代码 this.state.timeId = setTimeout(function(){
// 递归调用,实现 setInterval 方法
_self.autoChange();
},1000);
}
handleClick(e){ // 用点击模拟红路灯 if(this.state.timeId){
clearTimeout(this.state.timeId);
this.state.timeId = null;
} else {
this.autoChange();
} }
render(){
// 通过connect 注入 redux 的 dispatch 方法
return (
<div id="traffic" onClick={this.handleClick}>
<Light light={'yellow'}/>
</div>
)
}
}

上面的代码还是个半成品,看不到效果;简单描述一下上面的代码做了什么:

  • 定义App容器,将 Light 组件放在其render方法中
  • constructor 方法引用了 _bind 方法,方便一次性绑定this上下文,该方法来自文章Refactoring React Components to ES6 Classes
  • handleClick 方法是纯粹是为了演示,当用户点击红绿灯的时候,红绿灯调用 autoChange方法 开始自动变换,用户再次点击的时候就停止变换;
  • autoChange 方法用于红绿灯状态自动转换的,这里占位;本质是使用setTimeout代替setInterval实现;

2.3、链接React组件和Redux类

这是最为关键的一个步骤,

class App extends Component{

    ...
} // 声明 connect 连接
// 将 redux 中的 state传给 App
function mapStateToProps(state){
return{
light:state
}
} function mapDispatchToProps(dispatch){
return{
actions : bindActionCreators(LightActions,dispatch)
}
} // 声明 connect 连接
App = connect(mapStateToProps,mapDispatchToProps)(App); // 真正的连接
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('demo')
)

这里使用 react-redux 提供connect的方法 链接React组件和Redux类

// 声明 connect 连接
App = connect(mapStateToProps,mapDispatchToProps)(App);
  • connect 方法不会改变原来的组件类,反而返回一个新的 已与 Redux store 连接的 组件类。注意这里并没有注入store对象,真正store对象的注入靠最后的&lt;Provider store&gt;组件;(更多说明请参考 [react-redux 的 API][1])
  • 传入 connectmapStateToProps方法 ,正如其名,是将 Redux 的状态 映射到 React组件的props属性。任何时候,只要 Redux store 发生改变,mapStateToProps 函数就会被调用。这里返回对象是{light:state},这样确保 Redux 中的 state 发生改变时,组件的 props.light 都是最新的 Redux state。
  • mapDispatchToProps方法 则是将 Store 中的 dispatch方法 直接封装成对象的一个属性,一般会用到 Redux 的辅助函数bindActionCreators();这里将dispatch绑定到action属性,这样在红绿灯组件内让其变成红灯的时候,不需要dispatch(changeRed())这么调用,直接使用actions.changeRed(),语义化更好;(更多说明请参考 [react-redux 的 API][1])
  • 最后的&lt;Provider store&gt;使组件层级中的 connect() 方法都能够获得 Redux store ,这里才真正注入store变量,之前的只是声明而已(之前的好比store是个形参,到了这一步store就是实参了)。(更多说明请参考 [react-redux 的 API][1])

经过上面的语句,Redux就将 state属性 、 (store 的)dispatch方法与 React 组件的 props 绑定在一起,凡是更改 redux 的 states,就会更新所连接组件的props属性。

react-redux 中的 connect 方法就算是HOC(High Order Component,高阶组件)了,具体原理可参考文章初识React中的High Order Component,这是因为如果使用ES6 写React组件的话,mixin是不支持的,因此使用High Order Component代替;

2.4、利用redux驱动react

理解了最为困难的部分,之后的事情就水到渠成了;

现在,只要记住 在App中可以直接使用Redux中的一切了 就行了

我们回过头来,完善App组件的代码,完善 autoChange 方法:

class App extends Component{
_bind(...methods){
methods.forEach((method)=>this[method] = this[method].bind(this));
}
constructor(){
super();
this._bind('changeColor','handleClick','autoChange');
this.state = {
count : 0,
timeId : null
}
}
changeColor(light,actions){ // 红路灯变换规则
switch(light.color){
case 'red':
actions.changeGreen();
break;
case 'green':
actions.changeYellow();
break;
case 'yellow':
actions.changeRed();
break;
default:
actions.changeRed();
}
}
autoChange(){ // 自动更改红绿灯
const { light, actions } = this.props;
let _self = this; let curCount = ++this.state.count; // console.log('xx,',curCount);
if(this.state.count > +light.time){
curCount = 0;
this.changeColor(light,actions);
}
// 自动更改
this.state.timeId = setTimeout(function(){
_self.setState({count:curCount});
_self.autoChange();
},1000); }
handleClick(e){ // 用点击模拟红路灯 if(this.state.timeId){
clearTimeout(this.state.timeId);
} else {
this.autoChange();
} }
render(){
// 通过connect 注入 redux 的 dispatch 方法
const { light, actions } = this.props;
return (
<div id="traffic" onClick={this.handleClick.bind(this)}>
<Light light={light}/>
</div>
)
}
}

至此已经完成本节示例,通过npm start开启服务, 在 http://localhost:3000/light/redux 中查看。

在这个示例里,通过点击红绿灯,每隔若干秒红绿灯就会变换颜色,这说明两者已经链接起来;

(这个是gif图,如果没动画请点击在新窗口打开)

在后一篇文章,将示例如何处理多个Redux、React的情形;

[1]http://camsong.github.io/redux-in-chinese/docs/react-redux/api.html

Redux教程2:链接React的更多相关文章

  1. 【前端,干货】react and redux教程学习实践(二)。

    前言 这篇博文接 [前端]react and redux教程学习实践,浅显易懂的实践学习方法. ,上一篇简略的做了一个redux的初级demo,今天深入的学习了一些新的.有用的,可以在生产项目中使用的 ...

  2. react+redux教程(五)异步、单一state树结构、componentWillReceiveProps

    今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...

  3. react+redux教程(四)undo、devtools、router

    上节课,我们介绍了一些es6的新语法:react+redux教程(三)reduce().filter().map().some().every()....展开属性 今天我们通过解读redux-undo ...

  4. react+redux教程(二)redux的单一状态树完全替代了react的状态机?

    上篇react+redux教程,我们讲解了官方计数器的代码实现,react+redux教程(一).我们发现我们没有用到react组件本身的state,而是通过props来导入数据和操作的. 我们知道r ...

  5. redux 介绍及配合 react开发

    前言 本文是 Redux 及 Redux 配合 React 开发的教程,主要翻译自 Leveling Up with React: Redux,并参考了 Redux 的文档及一些博文,相对译文原文内容 ...

  6. Redux教程1:环境搭建,初写Redux

    如果将React比喻成士兵的话,你的程序还需要一位将军,去管理士兵(的状态),而Redux恰好是一位好将军,简单高效: 相比起React的学习曲线,Redux的稍微平坦一些:本系列教程,将以" ...

  7. react,react-router,redux+react-redux 构建一个React Demo

    创建初始化应用 加速我们的npm. npm install -g cnpm --registry=https://registry.npm.taobao.org 利用create-react-app ...

  8. Redux管理你的React应用

    使用Redux管理你的React应用   因为redux和react的版本更新的比较频繁,博客园这里用的redux版本是1.0.1,如果你关心最新版本的使用技巧,欢迎来我的Github查看(https ...

  9. react+redux教程(八)连接数据库的redux程序

    前面所有的教程都是解读官方的示例代码,是时候我们自己写个连接数据库的redux程序了! 例子 这个例子代码,是我自己写的程序,一个非常简单的todo,但是包含了redux插件的用法,中间件的用法,连接 ...

随机推荐

  1. html5悬浮球效果

    自己想做一个自己的网站,觉得自适应的效果会好一点,但是放到手机端的话,菜单显示是个问题.所以自己试着写了一个悬浮球菜单的效果. 好了,上代码. 这里有四个文件要用: jqurey.js//因为基于jq ...

  2. LINUX安全加固规范

    1 概述 近几年来Internet变得更加不安全了.网络的通信量日益加大,越来越多的重要交易正在通过网络完成,与此同时数据被损坏.截取和修改的风险也在增加. 只要有值得偷窃的东西就会有想办法窃取它的人 ...

  3. SQL 存储过程 分页查询

    ALTER PROCEDURE [dbo].[gzProc_TablePage] @tablename varchar(MAX),--表名 @selcolumn varchar(MAX),--查询字段 ...

  4. Python -- 数据加载、存储与文件格式

    标签(空格分隔): Python 读入读出通常可以划分为几个大类:读取文本文件和其他更高效的磁盘存储格式,加载数据库中的数据,利用Web API操作网络资源. 读写文本格式的数据 pandas提供了一 ...

  5. [POJ2069]Super Star(模拟退火)

    题目链接:http://poj.org/problem?id=2069 题意:求一个半径最小的球,使得它可以包围住所有点. 模拟退火,圆心每次都去找最远那个点,这样两点之间的距离就是半径,那么接下来移 ...

  6. 16-阿里-intership

  7. HTML转义字符大全

    ISO Latin-1字符集:  — 制表符Horizontal tab  — 换行Line feed  — 回车Carriage Return  — Space ! ! — 惊叹号Exclamati ...

  8. .NET开源项目

      综合类 微软企业库 微软官方出品,是为了协助开发商解决企业级应用开发过程中所面临的一系列共性的问题, 如安全(Security).日志(Logging).数据访问(Data Access).配置管 ...

  9. linux内核学习心得

    最初在其他课程做实验的时候接触到了linux,震撼于linux的开源精神,想更了解linux的内部原理,选了这门课程.通过这门课程对linux内部实现有了一定的了解,主要是中断.进程切换.系统函数的具 ...

  10. Centos6.5下的Hadoop安装

    开始进行云计算部分的学习,为了存档,写下现在进行过的步骤 需要用到的主要版本: 虚拟机:Vmware Workstation pro 12.5 Linux系统:CentOS6.4 64bit jdk版 ...