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,也就是要進行事件的訂閱
最后的步驟:
- 引入 actionCreators
- 事件訂閱
- 事件發布
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;

好了,功能完成了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/333820.html
標籤:其他
下一篇:Vue中diff演算法詳解
