Flux使用流程
- 要想使用FLux架构思维,需要通过一个工具进行使用, 这个工具就是flux
- 安装 flux
$ yarn add flux
- 在src目录下 新建store目录,里面新建index.js
- store有两个功能
- 存储数据
- 当数据发生改变时,视图要进行更新 ( 当前组件中的state发生了改变,从新从store中获取数据,要想重新复制,那么要通过事件的发布,订阅 )
- store有两个功能
// store/index.js
/*
打造store
1. 存储数据
2. 通过事件将新的数据反映到 View 层
*/
const EventEmitter = require( 'events' ).EventEmitter
// EventEmitter.prototype身上有 on emit 事件的发布和订阅的能力
// 将 on emit 两个方法给store
const store = {
...EventEmitter.prototype,
state: {//数据存储
count: 0
},
getState () {//获取 store 中的数据的
return this.state// 这里的this指的就是store
}
}
export default store
- 将store中的数据显示在组件(视图)中
import store from './store'
class xxx extends React.Component{
constructor () {
super()
this.state = {
count: store.getState().count
}
}
render () {
return (
<div>
<p> { this.state.count } </p>
</div>
)
}
}
-
用户操作,用户点击按钮,执行当前组件中的方法,这个方法的逻辑实际上是actionCreators中的方法
-
创建actionCreators.js
- actions的发送要通过dispatcher来发送
/* actionCreators 1. 用于View 和 用户交互 2. 用来创建一个动作,然后发送给 Dispatcher 3. actionCreators也是对象,里面存储的是方法 4. actionCreators中的动作的发送者要靠 Dispatcher 中的方法来提供 */ import * as type from './type' import dispatcher from './dispatcher'; const actionCreators = { increment () { // 创建动作 let actions = { type: type.INCRMENT } // dispatcher来通过dispatch 发送actions dispatcher.dispatch( actions ) } } export default actionCreators
-
创建dispatcher.js
/* Dispatcher 1. 修改数据 2. 直接用户操作 */ import { Dispatcher } from 'flux';//引入Dispatcher模块 import * as type from './type' import state from './state' const dispatcher = new Dispatcher() // dispatcher.register( callback ) // 判断用户进行了哪些用户交互 dispatcher.register( ( actions) => { switch ( actions.type ) { case type.INCRMENT: // 用户操作了 state.count++ break; default: break; } }) export default dispatcher
-
通过store的事件的发布和订阅进行 当前组件中 state 的重新赋值
import React from 'react';
import logo from './logo.svg';
import './App.css';
import store from './store'
import actionCreators from './store/actionCreators';
class App extends React.Component {
constructor () {
super()
this.state = {
count: store.getState().count
}
}
increment () {
actionCreators.increment()
store.emit('count')//事件的订阅
}
componentDidMount () {
//进行store 事件的发布
store.on('count', () => {
this.setState({
count: store.getState().count
})
})
}
render () {
return (
<div>
<h3> flux </h3>
<button onClick = { this.increment }> + </button>
<p> count: { this.state.count } </p>
</div>
)
}
}
export default App;