因工作需要使用 React + Reflux 开发,最近几天都在努力学习着,特别是 Reflux,在网上查找的许多资料和 github 上的文档年代都有点久远,JavaScript 按照目前的节奏,更新得太快,旧文档的一些语法跟不上更新,对广大初学者来说,确实存在许多困惑。本文是仅适于初学者或对 React 感兴趣的朋友,大神请绕道!!!

  废话不多说,进入正题~

  引用俗话:“学语言用 hello world,学框架用 todolist”,今天咱们就用 todolist 来做说明。

  作为一个对比 todolist-raw 是没有用 Reflux 实现 todolist 的增加和删除的,react-reflux 使用 Reflux 实现 todolist 的增加和删除,react-reflux 又分基本关联和简便法关联 Component。

  先看下组件的效果图:

  

  电脑需要准备好环境,我用的是 create-react-appyarn ,请自行百度安装好这两个工具,项目目录精简如下图:

  

  1. todolist-raw 就几个文件,里面的代码都比较简单,相信各道友一看就懂了。

package.json 的配置如下:

 1 {
 2   "name": "todolist-raw",
 3   "version": "0.1.0",
 4   "private": true,
 5   "dependencies": {
 6     "react": "^16.4.1",
 7     "react-dom": "^16.4.1",
 8     "react-scripts": "1.1.4"
 9   },
10   "scripts": {
11     "start": "react-scripts start",
12     "build": "react-scripts build",
13     "test": "react-scripts test --env=jsdom",
14     "eject": "react-scripts eject"
15   }
16 }
View Code

这里注意一下版本,版本不对应我也不知道会出现什么样的问题,比如我用的是 yarn 安装了 Rflux 之后, 提示 "react-scripts" 不是内部命令,yarn start 启动不了,反复试验都不行,后来打扣了 yarn -h 然后接着 yarn -autoclean 就好了。讲了那么多,其实我遇到的这个问题也不算版本不对称的问题吧,建议出现一些莫名其妙的 bug 就整理下 yarn。痒?痒就挠呗!!!

index.html 如下:与自动生成的没什么改变,就是删了一些注释!

 1 <!DOCTYPE html>
 2 <html lang="en">
 3   <head>
 4     <meta charset="utf-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 6     <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
 7     <title>TodoList-raw</title>
 8   </head>
 9   <body>
10     <noscript>
11       You need to enable JavaScript to run this app.
12     </noscript>
13 
14     <div id="root"></div>
15 
16   </body>
17 </html>
View Code

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 如下:

 1 import React, { Component, Fragment } from 'react';
 2 import Items from './Items';
 3 
 4 class TodoList extends Component {
 5 
 6   constructor(props) {
 7     super(props);
 8     this.state = {
 9       items: [1, 2, 3],
10       isC: false
11     };
12 
13     this.handlerClick = this.handlerClick.bind(this);
14   }
15   // 添加一个 item 项
16   handlerClick() {
17     const val = this.refs.inputEl.value;
18     this.refs.inputEl.value = '';
19     const items = [...this.state.items, val]; // 最好不要直接操作 state
20     this.setState({items}); // es6 语法,等价于 {items: items}
21     }
22 
23   // 删除某一个 item 项,点击就删除
24   handlerDelete(index) {
25     const items = [...this.state.items];
26     items.splice(index, 1);
27     this.setState({items}); 
28   }
29 
30   render() {
31     return (
32       <Fragment>
33         <h3>Hello React!</h3>
34         <input
35           ref="inputEl"
36           style={{marginRight: "10px"}}
37         />
38         <button onClick={this.handlerClick}>添加</button>
39         <Items
40           msg={this.state.items}
41           func={this.handlerDelete.bind(this)} />
42       </Fragment>
43     );
44   }
45 }
46 
47 export default TodoList;
View Code

说明几点:

  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 代码如下:

 1 import React, { Component } from 'react';
 2 
 3 class Items extends Component {
 4 
 5   constructor(props) {
 6     super(props);
 7     this.func = this.props.func;
 8   }
 9 
10   render() {
11     return (
12       <ul>
13         {this.props.msg.map((item, index) => <li
14             key={index}
15             onClick={this.func.bind(this, index)}
16           >{item}</li>
17         )}
18       </ul>
19     );
20   }
21 }
22 
23 export default Items;
View Code

 注意,父组件传递方法给子组件时,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 代码如下:

1 import Reflux from 'reflux';
2 
3 const TodoActions = Reflux.createActions([
4     'getAll',
5     'addItem',
6     'deleteItem'
7 ]);
8 export default TodoActions;
View Code

TodoStore.js 代码如下:

 1 import Reflux from 'reflux';
 2 import Actions from './TodoActions';
 3 
 4 const TodoStore = Reflux.createStore({
 5 
 6     // items: [1, 2, 3],
 7     // listenables: Actions,
 8 
 9     init() {
10         console.log('TodoStore init method~');
11         this.items = [1, 2, 3]; // 给个初始值
12         this.listenables = Actions; // 监听 TodoActions.js
13         // this.listenTo(addItem, 'addItem');
14     },
15     onGetAll() {
16         console.log('onGetAll');
17         this.trigger(this.items);
18     },
19     onAddItem(model) {
20         console.log('onAddItem---', model);
21         this.items.unshift(model);
22         this.trigger(this.items);
23     },
24     onDeleteItem(index) {
25         console.log('onDeleteItem---', index);
26         this.items.splice(index, 1);
27         this.trigger(this.items);
28     }
29 })
30 
31 export default TodoStore;
View Code

说明:多个监听用 listenables,单个监听 this.listenTo(addItem, 'addItem'); 多个监听的时候定义处理函数是 on + ActionName 驼峰式命名。定义初始值和监听可以写在 init 方法外面,就像上面那样(已注释)。

  2.5 Actions 和 Store 都写好了,就差最后一步,整合到组件 Component 中,才算有点意义了!TodoList.js 代码如下:

 1 import React, { Component, Fragment } from 'react';
 2 import Actions from './TodoActions';
 3 import TodoStore from './TodoStore';
 4 import Items from './Items';
 5 
 6 class TodoList extends Component {
 7 
 8     constructor(props) {
 9         super(props);
10         this.state = {
11             items: [],
12             isC: false
13         };
14 
15         this.handlerClick = this.handlerClick.bind(this);
16     }
17     // 组件挂载
18     componentDidMount() {
19         this.unsubscribe = TodoStore.listen(this.onStatusChange, this);
20         Actions.getAll();
21     }
22     // 组件移除
23     componentWillUnmount() {
24         console.log('componentWillUnmount');
25         this.unsubscribe(); // 解除监听
26     }
27     // callback
28     onStatusChange(items) {
29         this.setState({items});
30     }
31     // 添加一个 item 项
32     handlerClick() {
33         const val = this.refs.inputEl.value;
34         this.refs.inputEl.value = '';
35         Actions.addItem(val);
36     }
37 
38     render() {
39         return (
40             <Fragment>
41                 <h3>Hello React-Reflux!</h3>
42                 <input
43                     ref="inputEl"
44                     style={{marginRight: "10px"}}
45                 />
46                 <button onClick={this.handlerClick}>添加</button>
47                 <Items msg={this.state.items} />
48             </Fragment>
49         );
50     }
51 }
52 
53 export default TodoList;
View Code

 说明:这是基本的添加关联,需要在组件挂载时监听 Store,需要定义一个回调函数 onStatusChange(),组件卸载时解除监听 this.unsubscribe(),Store 源码如下:

不传 bindContext 更新不了状态,回调函数 onStatusChange 中报异常,传入 this 就好了。如图:

Items.js 代码如下:

 1 import React, { Component } from 'react';
 2 import Actions from './TodoActions';
 3 
 4 class Items extends Component {
 5     render() {
 6         return (
 7             <ul>
 8                 {this.props.msg.map((item, index) => <li
 9                         key={index}
10                         onClick={this.handlerDelete.bind(this, index)}
11                     >{item}</li>
12                 )}
13             </ul>
14         );
15     }
16     handlerDelete(index) {
17         Actions.deleteItem(index);
18     }
19 }
20 
21 export default Items;
View Code

  3. react-reflux: 通过 Reflux 来实现简单的 TodoList (简便法关联 Component)。

  3.1 先安装 react-mixinaxios: npm install react-mixin,npm install axios。结合异步操作实现简便 Store 关联 Component。

安装两个依赖之后,修改 TodoStore.js 和 TodoList.js 代码如下:

我贴:TodoStore.js:

 1 import Reflux from 'reflux';
 2 import Actions from './TodoActions';
 3 import Axios from 'axios';
 4 
 5 const TodoStore = Reflux.createStore({
 6 
 7     // items: [3, 2, 1],
 8     // listenables: Actions,
 9 
10     init() {
11         console.log('TodoStore init method~');
12         this.items = [3, 2, 1]; // 初始值,此处不是 state, mark-1 -2 -3 都可以直接操作
13         this.listenables = Actions;
14     },
15     onGetAll() {
16         console.log('onGetAll');
17         Axios.get('https://api.github.com/')
18         .then(res => {
19             const keys = Object.keys(res.data);
20             console.log('axios-response-keys: ', keys);
21             this.items = keys; // mark-1
22             this.trigger(this.items);
23         })
24         .catch(err => console.log('axios-error: ', err));
25     },
26     onAddItem(model) {
27         console.log('onAddItem---', model);
28         this.items.unshift(model); // mark-2
29         console.log('TodoStore-items: ', this.items);
30         this.trigger(this.items);
31     },
32     onDeleteItem(index) {
33         console.log('onDeleteItem---', index);
34         this.items.splice(index, 1); // mark-3
35         this.trigger(this.items);
36     }
37 })
38 
39 export default TodoStore;
View Code

我再贴:TodoList.js:

 1 import React, { Component, Fragment } from 'react';
 2 import ReactMixin from 'react-mixin';
 3 import Reflux from 'reflux';
 4 import Actions from './TodoActions';
 5 import TodoStore from './TodoStore';
 6 import Items from './Items';
 7 
 8 class TodoList extends Component {
 9 
10     constructor(props) {
11         super(props);
12         this.state = {
13             items: [],
14             isC: false
15         };
16 
17         this.handlerClick = this.handlerClick.bind(this);
18     }
19     // 组件挂载
20     componentDidMount() {
21         Actions.getAll();
22     }
23     // 添加一个 item 项
24     handlerClick() {
25         const val = this.refs.inputEl.value;
26         this.refs.inputEl.value = '';
27         if (!val) {
28             alert('Please enter the data which type of number or string');
29             return false;
30         }
31         Actions.addItem(val);
32     }
33 
34     render() {
35         return (
36             <Fragment>
37                 <h3>Hello React-Reflux!</h3>
38                 <input
39                     ref="inputEl"
40                     style={{marginRight: "10px"}}
41                 />
42                 <button onClick={this.handlerClick}>添加</button>
43                 <Items msg={this.state.items} />
44             </Fragment>
45         );
46     }
47 }
48 // 用 Reflux.connect 将 Store 和 Component 组合在一起
49 ReactMixin.onClass(TodoList, Reflux.connect(TodoStore, 'items'));
50 
51 export default TodoList;
View Code

修改之后 yarn start 启动项目,截图如下:

   4. 说在后面的话:本篇文章只是关于 React-Reflux 基础入门的一些知识,没有涉及实战应用,读者自酌。对于 React 我也是初学者,难免有许多不准确的地方,有待提高,欢迎各位道友留言指正。

  4.1 好了,简单地分享就到此结束了,谢谢阅读~~~

  5. 参考资料:

  https://github.com/reflux/refluxjs#creating-actions

  https://blog.csdn.net/starwmx520/article/details/50774210

  https://segmentfault.com/a/1190000002793786

  https://blog.csdn.net/u012677935/article/details/51917133?locationNum=9

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程