您好,欢迎访问一九零五行业门户网

React-Reflux的基础介绍

这篇文章主要介绍了关于react-reflux的基础介绍,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
因工作需要使用 react + reflux 开发,最近几天都在努力学习着,特别是 reflux,在网上查找的许多资料和 github 上的文档年代都有点久远,javascript 按照目前的节奏,更新得太快,旧文档的一些语法跟不上更新,对广大初学者来说,确实存在许多困惑。本文是仅适于初学者或对 react 感兴趣的朋友,大神请绕道!!!
废话不多说,进入正题~
引用俗话:“学语言用 hello world,学框架用 todolist”,今天咱们就用 todolist 来做说明。
作为一个对比 todolist-raw 是没有用 reflux 实现 todolist 的增加和删除的,react-reflux 使用 reflux 实现 todolist 的增加和删除,react-reflux 又分基本关联和简便法关联 component。
先看下组件的效果图:
电脑需要准备好环境,我用的是 create-react-app 和 yarn ,请自行百度安装好这两个工具,项目目录精简如下图:
1. todolist-raw 就几个文件,里面的代码都比较简单,相信各道友一看就懂了。
package.json 的配置如下:
{ "name": "todolist-raw", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.4.1", "react-dom": "^16.4.1", "react-scripts": "1.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }}
这里注意一下版本,版本不对应我也不知道会出现什么样的问题,比如我用的是 yarn 安装了 rflux 之后, 提示 "react-scripts" 不是内部命令,yarn start 启动不了,反复试验都不行,后来打扣了 yarn -h 然后接着 yarn -autoclean 就好了。讲了那么多,其实我遇到的这个问题也不算版本不对称的问题吧,建议出现一些莫名其妙的 bug 就整理下 yarn。痒?痒就挠呗!!!
index.html 如下:与自动生成的没什么改变,就是删了一些注释!
<!doctype html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="shortcut icon" href="%public_url%/favicon.ico"> <title>todolist-raw</title> </head> <body> <noscript> you need to enable javascript to run this app. </noscript> <div id="root"></div> </body></html>
index.js 如下:
1 import react from 'react';2 import reactdom from 'react-dom';3 import todolist from './todolist';4 5 reactdom.render(<todolist />, document.getelementbyid('root'));
view code
todolist.js 如下:
import react, { component, fragment } from 'react';import items from './items';class todolist extends component { constructor(props) { super(props); this.state = { items: [1, 2, 3], isc: false }; this.handlerclick = this.handlerclick.bind(this); } // 添加一个 item 项 handlerclick() { const val = this.refs.inputel.value; this.refs.inputel.value = ''; const items = [...this.state.items, val]; // 最好不要直接操作 state this.setstate({items}); // es6 语法,等价于 {items: items} } // 删除某一个 item 项,点击就删除 handlerdelete(index) { const items = [...this.state.items]; items.splice(index, 1); this.setstate({items}); } render() { return ( <fragment> <h3>hello react!</h3> <input ref="inputel" style={{marginright: "10px"}} /> <button onclick={this.handlerclick}>添加</button> <items msg={this.state.items} func={this.handlerdelete.bind(this)} /> </fragment> ); }}export default todolist;
说明几点:
a. this.handlerclick = this.handlerclick.bind(this); 是用来绑定 this 的,react 用的是 jsx 语法糖,整个 js 就是一个组件,在标签上绑定事件是不能带括号的,如果像传统的 html 事件绑定那样绑事件不行,因为这个标签就是在 js 文件中的,像传统的 html 绑定事件就会直接调用了!所以 jsx 中的标签绑定事件绑的是引用。而且需要绑定在这个 js 文件(组件)上。所以 jsx 中的标签的事件就是 <button onclick={this.handlerclick.bind(this, param_1, ..., param_n)}></button>.这只是我的理解,不知道对不对,如果不正确,请指正!
b. 代码很少阅读起来应该没难度,而且上面也有一些注释了。不过还是要啰嗦一下。react 是用数据(data)基于状态(state)来驱动视图(view),也就是搞来搞去都是在搞数据,用数据改变状态来达到渲染视图的目的,大多是在虚拟内存处理,通过什么 diff 比较算法,层层计较然后达到提高性能,加快视图渲染的目的。额,我只能用“非常快”来形容 react 的性能,当然,性能的事还是跟实际代码复杂度相关,我只想说 react 确实出众!扯远了...,既然是基于状态(state),所以要有 state,在 constructor 中定义了,而且处理业务时改变 state,比如 handlerclick,deleteclick 中都是先用变量保存下来,通过 this.setstate() 方法在设置回去!
c. 父子关系的组件,父组件可通过属性来给子组件传参,就像这样:<items msg={this.state.items} />,子组件可通过 this.props.msg 拿到 items。
items.js 代码如下:
import react, { component } from 'react';class items extends component { constructor(props) { super(props); this.func = this.props.func; } render() { return ( <ul> {this.props.msg.map((item, index) => <li key={index} onclick={this.func.bind(this, index)} >{item}</li> )} </ul> ); }}export default items;
注意,父组件传递方法给子组件时,this 指向的是子组件,所以通过属性传递时,需要用函数绑定 bind() 绑定父组件的 this。
最后,通过 cmd 命令行,yarn start 运行任务即可实现一个简单的 todolist 功能。
2. react-reflux: 通过 reflux 来实现简单的 todolist (基本法关联 component)。
2.1 简单地说明下为什么要 reflux 架构,如图(自己画的组件树结构!),不存在父子关系的组件(如 b 和 e)通讯势必会很困难而且麻烦,需要一个中间件(store)来存储数据,类似于订阅者和发布者(中间人模式)一样,大家都往 store 中存取数据就好,不需要层层走关系了,避免了层层传递数据的灾难!
2.2 关于 actions、store 和 component 的关系,可以这么理解:store 作为一个中间人有订阅和发布的功能,actions 就是 component 触发的动作,actions 被 store 监听着,组件有新动作了, store 就会做出相应的处理(回调函数)更改 store 中的数据通过 this.trigger(this.items) 发布消息[就相当于更新 items], component 监听着 store,用一些手段(mixin 或回调函数)关联起 component 中的状态信息(state.items)和 store 中的信息(items),这就是所谓的单向数据流,单向表示一个方向流动,不能反向。
2.3 目录结构和前面的 todolist-raw 没多大区别,就是多了 todoactions.js 和 todostore.js 两个文件。如图:
2.4 一言不合就贴代码。首先 index.js 代码没变化,就不贴了,todoactions.js 代码如下:
import reflux from 'reflux';const todoactions = reflux.createactions([ 'getall', 'additem', 'deleteitem']);export default todoactions;
todostore.js 代码如下:
import reflux from 'reflux';import actions from './todoactions';const todostore = reflux.createstore({ // items: [1, 2, 3], // listenables: actions, init() { console.log('todostore init method~'); this.items = [1, 2, 3]; // 给个初始值 this.listenables = actions; // 监听 todoactions.js // this.listento(additem, 'additem'); }, ongetall() { console.log('ongetall'); this.trigger(this.items); }, onadditem(model) { console.log('onadditem---', model); this.items.unshift(model); this.trigger(this.items); }, ondeleteitem(index) { console.log('ondeleteitem---', index); this.items.splice(index, 1); this.trigger(this.items); }})export default todostore;
说明:多个监听用 listenables,单个监听 this.listento(additem, 'additem'); 多个监听的时候定义处理函数是 on + actionname 驼峰式命名。定义初始值和监听可以写在 init 方法外面,就像上面那样(已注释)。
2.5 actions 和 store 都写好了,就差最后一步,整合到组件 component 中,才算有点意义了!todolist.js 代码如下:
import react, { component, fragment } from 'react';import actions from './todoactions';import todostore from './todostore';import items from './items';class todolist extends component { constructor(props) { super(props); this.state = { items: [], isc: false }; this.handlerclick = this.handlerclick.bind(this); } // 组件挂载 componentdidmount() { this.unsubscribe = todostore.listen(this.onstatuschange, this); actions.getall(); } // 组件移除 componentwillunmount() { console.log('componentwillunmount'); this.unsubscribe(); // 解除监听 } // callback onstatuschange(items) { this.setstate({items}); } // 添加一个 item 项 handlerclick() { const val = this.refs.inputel.value; this.refs.inputel.value = ''; actions.additem(val); } render() { return ( <fragment> <h3>hello react-reflux!</h3> <input ref="inputel" style={{marginright: "10px"}} /> <button onclick={this.handlerclick}>添加</button> <items msg={this.state.items} /> </fragment> ); }}export default todolist;
说明:这是基本的添加关联,需要在组件挂载时监听 store,需要定义一个回调函数 onstatuschange(),组件卸载时解除监听 this.unsubscribe(),store 源码如下:
不传 bindcontext 更新不了状态,回调函数 onstatuschange 中报异常,传入 this 就好了。如图:
items.js 代码如下:
import react, { component } from 'react';import actions from './todoactions';class items extends component { render() { return ( <ul> {this.props.msg.map((item, index) => <li key={index} onclick={this.handlerdelete.bind(this, index)} >{item}</li> )} </ul> ); } handlerdelete(index) { actions.deleteitem(index); }}export default items;
3. react-reflux: 通过 reflux 来实现简单的 todolist (简便法关联 component)。
3.1 先安装 react-mixin 和 axios: npm install react-mixin,npm install axios。结合异步操作实现简便 store 关联 component。
安装两个依赖之后,修改 todostore.js 和 todolist.js 代码如下:
我贴:todostore.js:
import reflux from 'reflux';import actions from './todoactions';import axios from 'axios';const todostore = reflux.createstore({ // items: [3, 2, 1], // listenables: actions, init() { console.log('todostore init method~'); this.items = [3, 2, 1]; // 初始值,此处不是 state, mark-1 -2 -3 都可以直接操作 this.listenables = actions; }, ongetall() { console.log('ongetall'); axios.get('https://api.github.com/') .then(res => { const keys = object.keys(res.data); console.log('axios-response-keys: ', keys); this.items = keys; // mark-1 this.trigger(this.items); }) .catch(err => console.log('axios-error: ', err)); }, onadditem(model) { console.log('onadditem---', model); this.items.unshift(model); // mark-2 console.log('todostore-items: ', this.items); this.trigger(this.items); }, ondeleteitem(index) { console.log('ondeleteitem---', index); this.items.splice(index, 1); // mark-3 this.trigger(this.items); }})export default todostore;
我再贴:todolist.js:
import react, { component, fragment } from 'react';import reactmixin from 'react-mixin';import reflux from 'reflux';import actions from './todoactions';import todostore from './todostore';import items from './items';class todolist extends component { constructor(props) { super(props); this.state = { items: [], isc: false }; this.handlerclick = this.handlerclick.bind(this); } // 组件挂载 componentdidmount() { actions.getall(); } // 添加一个 item 项 handlerclick() { const val = this.refs.inputel.value; this.refs.inputel.value = ''; if (!val) { alert('please enter the data which type of number or string'); return false; } actions.additem(val); } render() { return ( <fragment> <h3>hello react-reflux!</h3> <input ref="inputel" style={{marginright: "10px"}} /> <button onclick={this.handlerclick}>添加</button> <items msg={this.state.items} /> </fragment> ); }}// 用 reflux.connect 将 store 和 component 组合在一起reactmixin.onclass(todolist, reflux.connect(todostore, 'items'));export default todolist;
修改之后 yarn start 启动项目,截图如下:
4. 说在后面的话:本篇文章只是关于 react-reflux 基础入门的一些知识,没有涉及实战应用,读者自酌。对于 react 我也是初学者,难免有许多不准确的地方,有待提高,欢迎各位道友留言指正。
4.1 好了,简单地分享就到此结束了,谢谢阅读~~~
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
vue使用redux的方法
react实现点击选中的li高亮的方法
以上就是react-reflux的基础介绍的详细内容。
其它类似信息

推荐信息