- 要想使用FLux架构思维,需要通过一个工具进行使用, 这个工具就是flux
- 安装 flux
$ yarn add flux - 在src目录下 新建store目录,里面新建index.js
- store有两个功能
- 存储数据
- 当数据发生改变时,视图要进行更新 ( 当前组件中的state发生了改变,从新从store中获取数据,要想重新复制,那么要通过事件的发布,订阅 )
- store有两个功能
// store/index.js
const EventEmitter = require( 'events' ).EventEmitter
const store = {
...EventEmitter.prototype,
state: {
count: 0
},
getState () {
return this.state
}
}
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来发送
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 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 的重新赋值
- 当我们点击按钮时,要通过store的事件的订阅给当前组件的state重新赋值,要想这样做,我们必须进行事件的发布
- 难点: 这个事件的发布往哪里写?
- 组件的生命周期中,数据可以进行一次修改的可以往 componentWillMount // componentDidMount
- 难点: 这个事件的订阅那里写?
- 当我们点击按钮的时候,就要修改当前组件的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.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;
Flux 的使用流程图

Flux是一个用于构建React应用的架构思想,主要通过flux工具进行实现。其核心流程包括:安装flux,创建store目录和index.js,store负责数据存储和视图更新。用户交互触发actionCreators中的方法,通过dispatcher发送actions。组件通过订阅store事件,在特定生命周期内如componentWillMount或componentDidMount中响应数据变化,更新state。难点在于确定事件发布的合适位置和订阅时机,通常在用户操作时订阅并在组件生命周期内更新state。
3144

被折叠的 条评论
为什么被折叠?



