React状态管理中fluex使用流程

Flux

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

     // store/index.jsconst 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.jsactions的发送要通过dispatcher来发送​
  ```javascript
     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;作业
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值