转载的~react

redux——入门1

2017-03-29  本文已影响25人  我只是个NPC

核心概念

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>
    );
  }
}
上一篇下一篇

猜你喜欢

热点阅读