前端文章收集

redux-thunk - redux的中间件

2017-11-10  本文已影响353人  胖太_91bf
redux-thunk是用来做异步的

他允许你的action可以返回函数, 带有dispatch和getState两个参数, 在这个action函数里, 异步的dispatch action;
action部分:

const GET_LIST = 'GET_LIST';

const getFetch = (data) => ({
    type: GET_LIST,
    data
})

export const getFetchData = () => (dispatch, getState) => {
  //先去请求数据
    fetch('http://localhost:1234/api/test/user/users')
        .then(res => {
            return res.json();
        })
        .then(data => {
            //请求数据完成后再dispatch
            dispatch(getFetch(data))
        })
        .catch(e => {
            console.log(e)
        })
}

reducer部分
const GET_LIST = 'GET_LIST';

export default (state = {}, action) => {
switch(action.type) {
case GET_LIST:
return action.data;
default:
return state
}
}
//用combineReducers()将所有reducer合并

import { combineReducers } from 'redux';
import todo from './todoReducer';
import filter from './filterReducer';
import fetch from './fetchReducer';

export default combineReducers({
    todo,
    filter,
    fetch
})

store部分

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';//引入异步中间件
import reducer from '../reduers';

const win = window;

const middleware = [];
if( process.env.NODE_ENV !== 'production' ) {
    //用于检查reducer是否改变的store的数据 react16已经弃用
    middleware.push(require('redux-immutable-state-invariant').default());
}
middleware.push(thunk);
const reduxEnhancers = compose(
    applyMiddleware(...middleware),
    (win && win.devToolsExtension ? win.devToolsExtension() : f => f)
);

export default createStore(reducer, {}, reduxEnhancers)

redux应用部分

import React, { PureComponent } from 'react';
import * as fetchDataFrom from '../../actions/fetchActions';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

class FetchData extends PureComponent {

    send() {
        this.props.fetchActions.getFetchData()
        console.log(1)
    }

    render() {
        console.log(this.props.fetch.success)
        return [
            <button onClick={this.send.bind(this)}>提交</button>,
            <p>{this.props.fetch.success && this.props.fetch.data[0].username}</p>

        ]
    }
}

//======== redux ==============
function mapStateToProps(state) {
    return {
        fetch: state.fetch
    }
}

function mapDispatchToProps(dispatch) {
    return {
        fetchActions: bindActionCreators(fetchDataFrom, dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(FetchData)
上一篇下一篇

猜你喜欢

热点阅读