ThoughtWorks创新实验室程序猿阵线联盟-汇总各类技术干货

Reflux 实现 hello world

2016-10-09  本文已影响133人  半生不熟_

初识Reflux

需求分析

分解任务

  1. 使用 React 创建一个组件,在页面渲染出 hello word
  2. 安装 Reflux
  3. 创建一个 Action
  4. 创建一个 Store,用来监听** Action **,并且获取 Action 传递的 hello world
  5. Store 将值传递给 Component,并且渲染到页面
  6. 将代码上传至 Github

分步实现任务

'use strict';

import React from 'react';
import {render} from 'react-dom';

const App = React.createClass({    
              render:function(){       
                      return <div>                    
                             hello world                
                       </div>   
     }
});
render(<App/>, document.getElementById("content"));

此时,使用 React 在页面渲染出 hello world

const store = Reflux.createStore({    
                   listenables: [action],   
                   onGetHello: function (hello) {      
                               this.trigger(hello);    
                  } 
});

使用 listenables 来监听 **action **,使用this.trigger() 来更新数据状态

const App = React.createClass({   
      mixins: [Reflux.connect(store, "hello")],  
      componentDidMount: function () {       
            action.getHello("hello world!");   
     },    
     render: function () {       
            return     <div>           
                 {this.state.hello}      
         </div>   
      }
  });

使用 mixinsstore 和 component 连接 ,使用action .getHello()调用action

深入理解Reflux

  1. 三大主要内容
  1. 单向数据流
        Action ———————> Store ——————> View Component
         ^
        └───────────────────────────────────┘

数据和操作在三者之间单向流动

  1. 数据流动问题
    Reflux 中主要由 Action 和 Store 组成,例:当组件 list 增加 Item 时,会调用Action 某个方法(如addItem(data)并将新的数据当参数传递进去,通过事件机制,数据会传送到 Store 中,Store 可以向服务器发送请求并提交给数据库,数据更新后,再通过事件机制传递到 list 当中,并更新 UI
  2. 与 Redux 的区别
  1. 优缺点

总结

  1. 学习过程中遇到的问题
  1. 经验
上一篇下一篇

猜你喜欢

热点阅读