redux-thunk - redux的中间件

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容