redux-thunk入门

  • A+
所属分类:React redux

$ npm install redux-thunk --save

文件结构:


├── src
│   ├── reducer
│       └── index.ts
│   ├── views
│       └── home.tsx
│   └── main.tsx
└── app.js

reducer->index.ts


/**
 * Created by pdslly on 2017/5/22.
 */

const ADD = 'ADD';
const REDUCE = 'REDUCE';

const doAddOrReduce = (state = 0, {type, payload = 0}) => {
    switch( type ){
        case ADD:
            state += payload;
            break;
        case REDUCE:
            state -= payload;
            break;
    }
    return state;
}

export default doAddOrReduce

views->home.tsx


/**
 * Created by pdslly on 2017/5/22.
 */

import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';

export interface HomeInter{
    addFn: Function,
    num: number
}

class Home extends Component<HomeInter, any>{

    constructor(props: HomeInter){
        super(props)
    }

    render(){
        const {addFn, num} = this.props;
        return (<button onClick={() => addFn()}>{num}<//button>)
    }
}

const mapStateToProps = (state, prop) => {
    return {
        num: state
    }
}

const addSync = (dispatch) => {
    setTimeout( () =>{dispatch({type: 'ADD', payload: 44})}, 3000 )
}

const mapDispatchToProps = (dispatch,props) => {
    return {
        addFn: () => {
            dispatch(addSync)
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Home)

main.tsx


import ReactDom from 'react-dom';
import React from 'react';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reduce from './reducer';
import thunk from 'redux-thunk';
import Home from './views/home.tsx'

const store = createStore( reduce, 55, applyMiddleware(thunk) );

ReactDom.render(
    <Provider store={store}>
        <Home/>
    </Provider>,
    document.querySelector('#main') )
weinxin
我的微信
欢迎来撩!!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: