react状态管理之flux

来源:互联网 发布:三国志9 知乎 编辑:程序博客网 时间:2024/05/29 02:29

flux逻辑理解

这里写图片描述

1.创建Actions
包括所有的动作,比如点击按钮添加列表项,这就是一个action,在action文件中直接用dispatcher方法来分配这个动作
action是用来暴露给外部进行调用

addNewItem: function (text) {  AppDispatcher.dispatch({    actionType: 'ADD_NEW_ITEM',    text: text  });},

2.创建store
store里面包含了应用的状态和逻辑,用来管理应用中不同的状态和逻辑
store中可以用数组来存储应用中所需要的数据,然后外部通过调用strore中的方法来获取到数据放到state中。

items: [],getAll: function () {  return this.items;},

3.创建dispacher
在dispatcher中通过register来给每个action注册对应的store中的方法

AppDispatcher.register(function (action) {  switch(action.actionType) {    case 'ADD_NEW_ITEM':      ListStore.addNewItemHandler(action.text);      ListStore.emitChange();      break;    default:      // no op  }})

4.在view层通过调用action中的方法来调用这个动作

  createNewItem: function (event) {    ButtonActions.addNewItem('new item');  },  render: function() {    return <MyButton      items={this.state.items}      onClick={this.createNewItem}    />;  }
原创粉丝点击