redux——入門1

weixin_33866037發表於2017-03-29

核心概念

redux中最核心的概念就三個,store,reducer,action,其間的資料流向關係是:

檢視層呼叫store.dispatch(action) => reducer處理action => store更新狀態後通知檢視層 => 檢視層更新

例子講解

下面以一個計數器的demo為例,進行例子講解

store.js

呼叫redux的createStore方法,建立一個store
createStore可以接受兩個引數,第一個reducer,第二個是state初始值,不傳則為undefined

import {createStore} from 'redux';
import reducer from '../reducer';

export default createStore(reducer);

reducer.js

reducer是一個純函式,接受兩個引數,第一個是state,第二個action

export default function(state = 0, action) {
  switch(action.type) {
    case 'INCREMENT': 
      return state + 1;
    case 'DECREMENT': 
      return state - 1;
    default:
      return state;
  }
}

counter.js

在counter.js中,需要注意的是在componentDidMount中,呼叫了store.subscribe(fn)方法進行了一個事件訂閱,就是說,在action完成,store的資料更新後,subscribe的fn會被執行

import React, {Component} from 'react';
import store from './store.js';

export default class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: store.getState()
    };
    this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    store.subscribe(this.onChange);
  }

  onChange() {
    this.setState({
      count: store.getState()
    });
  }

  increment() {
    store.dispatch({type: 'INCREMENT'});
  }

  decrement() {
    store.dispatch({type: 'DECREMENT'});
  }

  render() {
    return (
      <div>
        <h3>計數器</h3>
        <p>{this.state.count}</p>
        <button type="button" onClick={this.increment}>+++</button>
        <button type="button" onClick={this.decrement}>---</button>
      </div>
    );
  }
}

相關文章