redux沉思录

要素:store、reducer、dispatch/subscribe

connect:将业务逻辑剥离到容器类,数据的双向绑定;

数据、操作、UI分离、命令封装

核心思想:对共享状态的维护;

核心代码:

store={createStore(reducer)

const reducer = (state = 'GO', action) => {

  switch(action.type) {

     case 'GO':

        state = 'GO'

        break;

}

this.props.store.subscribe(() => {

      this.forceUpdate();

    });

<button onClick={() => {this.props.store.dispatch(goAction)}}

与flux的比较:

将状态修改的功能进行了剥离;

'use strict';

import React from 'react';

import ReactDOM from 'react-dom';

import Redux, { createStore } from 'redux';

import { reducer } from './reducer';

import { App } from './app';

ReactDOM.render(<App store={createStore(reducer)}/>,

                document.getElementById('root'))

'use strict';

import React, { Component } from 'react';

const stopColor = (store) => {

  return store.getState() == 'STOP' ? 'red' : 'white';

}

const cautionColor = (store) => {

  return store.getState() == 'CAUTION' ? 'yellow' : 'white';

}

const goColor = (store) => {

  return store.getState() == 'GO' ? 'rgb(39,232,51)' : 'white';

}

export class Stoplight extends Component {

  componentWillMount() {

    this.props.store.subscribe(() => {

      this.forceUpdate();

    });

  }

  render() {

    return(

      <div style={{textAlign: 'center'}}>

        <svg height='170'>

          <circle cx='145' cy='60' r='15'

                  fill={stopColor(this.props.store)}

                  stroke='black'/>

          <circle cx='145' cy='100' r='15'

                  fill={cautionColor(this.props.store)}

                  stroke='black'/>

          <circle cx='145' cy='140' r='15'

                  fill={goColor(this.props.store)}

                  stroke='black'/>

        </svg>

      </div>

    )

  }

}

'use strict';

import React, { Component } from 'react';

import { goAction, cautionAction, stopAction } from './actions';

export class Buttons extends Component {

  componentWillMount() {

    this.props.store.subscribe(() => {

      this.forceUpdate();

    });

  }

  render() {

    const state = this.props.store.getState();

    return(

      <div style={{textAlign: 'center'}}>

        <button onClick={() => {this.props.store.dispatch(goAction)}}

                disabled={state == 'GO' || state == 'CAUTION'}

                style={{cursor: 'pointer'}}>

          Go

        </button>

        <button onClick={() => {this.props.store.dispatch(cautionAction)}}

                disabled={state == 'CAUTION' || state == 'STOP'}

                style={{cursor: 'pointer'}}>

          Caution

        </button>

        <button onClick={() => {this.props.store.dispatch(stopAction)}}

                disabled={state == 'STOP' || state == 'GO'}

                style={{cursor: 'pointer'}}>

          Stop

        </button>

      </div>

    )

  }

}

猜你喜欢

转载自www.cnblogs.com/feng9exe/p/10880179.html
今日推荐