React-状态共享
Flux的使用流程
- 要想使用FLux架构思维,需要通过一个工具进行使用, 这个工具就是flux
- 安装 flux
$ yarn add flux
- 在src目录下 新建store目录,里面新建index.js
- store有两个功能
- 存储数据
- 当数据发生改变时,视图要进行更新 ( 当前组件中的state发生了改变,从新从store中获取数据,要想重新复制,那么要通过事件的发布,订阅 )
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 )
}
}
export default actionCreators
- 创建dispatcher.js