react-redux: async promise

1、the simple sample

action: 事实上,只是返回个一个至少包含type的对象{ },用于reducer接收。

import {RECEIVE_DATA} from "constant/ActionType";
import MessageService from "service/demo-service/MessageService";

const _messageService = new MessageService();

function receiveData(data) {
    return {
        type: RECEIVE_DATA,
        list: data
    }
}

export function fetchData() {
    return (dispatch) => {
        _messageService.getMessage().then(res => {
            dispatch(receiveData(res.data))
        })
    }
}

reducer:对应某个actionType有相应的数据返回

import {RECEIVE_DATA} from "constant/ActionType";

const initialState = {
    message: []
};

const MessageReducer = function (state = initialState, action) {
    switch (action.type) {
        case RECEIVE_DATA:
            return {message: action.list};
        default:
            return state;
    }
};
export default MessageReducer;

use:

const mapStateToProps = state => {
return {
messageList: state.MessageReducer.message
}
};
const mapDispatchToProps = {
fetchMessageList: fetchData
};
componentDidMount() {
this.props.fetchMessageList();
}

猜你喜欢

转载自www.cnblogs.com/Nyan-Workflow-FC/p/9316402.html
今日推荐