0
点赞
收藏
分享

微信扫一扫

React中的一个状态管理工具—Flux


Flux出现的原因

Flux的出现和传统MVC有关,因为传统的MVC架构没有解决,M和V之间的交互关系

为了弥补这个缺陷,人们相处了 Flux Redux Mobx 这样三种架构思维 , 那么React只是这三种架构的一个组成部分,那么这个组成部分充当的是 View( 视图 )

注意: Flux Redux Mobx 和 MVC 是同一级别的,相比之下, vuex级别要小的多 ,但是他们解决的都是多组件状态共享

问题:我想在Redux中使用vue , 可以吗? 可以的

Flux案例书写

案例中:点击 计数

要想使用FLux架构思维,需要通过一个工具进行使用, 这个工具就是flux

所以,我们需要安装Flux依赖-生产环境

yarn add flux

在src目录下 新建store目录,里面新建index.js

为什么store要拿到on和emit方法?

答:数据改变,视图更新( 要靠事件来执行,也就是要进行事件的订阅和发布 )

/*
当前的index.js文件就是 我们 flux组成部分中 store

store的功能:
1. 数据的存储者
2. 数据改变,视图更新( 要靠事件来执行,也就是要进行事件的订阅和发布 )
*/
const EventEmitter = require( 'events' ).EventEmitter

// console.log(EventEmitter.prototype) //打印发现on和emit方法在EventEmitter.prototype上

//将on和 emit解构在
const store = {
...EventEmitter.prototype,
state : {
count : 0
},
getState () {
return this.state
}
}

export default store

将store中的数据显示在组件(视图)中

import store from './store'

class App extends React.Component {

constructor () {
super()
this.state={
count : store.getState().count
}
}

render () {
let { count } = this.state
return (
<div className="App">
<p>count为: { count }</p>
</div>
)
}

}

export default App;

用户操作,用户点击按钮,执行当前组件中的方法,这个方法的逻辑实际上是actionCreators中的方法

创建actionCreators.js

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

import { Dispatcher } from 'flux'
import * as type from './type'
import store from './index'

const dispatcher = new Dispatcher()

//dispatcher.register( callback )

dispatcher.register( (actios) => {
switch( actios.type ) {
case type.INCRMENT:
store.state.count++;
break;
default:
break;
}
})

export default dispatcher

通过store的事件的发布和订阅进行 当前组件中 state 的重新赋值

  • 当我们点击按钮是,要通过store的事件的订阅给当前组件的state重新赋值,要想这样做,我们必须进行事件的发布
  • 难点: 这个事件的发布往哪里写?
  • 组件的生命周期中,数据可以进行一次修改的可以往 componentWillMount // componentDidMount
  • 难点: 这个事件的订阅那里写?
  • 当我们点击按钮的时候,就要修改当前组件的state,也就是要进行事件的订阅

最后的步骤:

  1. 引入 actionCreators
  2. 事件订阅
  3. 事件发布
import React from 'react';

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.on('count',()=>{//事件订阅
this.setState({
count : store.getState().count
})
})
}

render () {
let { count } = this.state
return (
<div className="App">
<button onClick={ this.increment }>count+</button>
<p>count为: { count }</p>
</div>
)
}

}

export default App;

React中的一个状态管理工具—Flux_react.js

好了,功能完成了




举报

相关推荐

0 条评论