redux——入门1

作者: 我只是个NPC | 来源:发表于2017-03-29 12:50 被阅读25次

    核心概念

    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>
        );
      }
    }
    

    相关文章

      网友评论

        本文标题:redux——入门1

        本文链接:https://www.haomeiwen.com/subject/cvyeottx.html