无法在Redux Reducer函数中解析Axios Promise

时间:2019-06-12 19:50:50

标签: javascript reactjs redux promise

我正在尝试从slack api获取频道列表,并将其存储在redux存储中并做出反应。

axios正在获得[[PromiseValue]],但我无法在其中获得对象:

归约文件:

import * as actionTypes from "../actions/types";
import { getChannels } from "./../services/channelService";

const channelsReducer = (state = getChannels(), action) => {
    switch (action.type) {
        case actionTypes.GET_CHANNELS:
            return state;

        default:
            return state;
    }
};

channelService.js文件:

import axios from "axios";

export const getChannels = async () => {
    const token =
        "token";
    return await axios
        .get(`https://slack.com/api/conversations.list?token=${token}`)
        .then(response => {
            return response.data;
        });
};

action.js文件:

import * as actionTypes from "./types";

export const getChannels = () => async dispatch => {
    dispatch({
        type: actionTypes.GET_CHANNELS
    });
};

和我的组件文件:

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as actions from "./../actions/channelsActions";

class Navbar extends Component {
    state = {};
    componentDidMount() {}
    render() {
        console.log(this.props.channels);
    }
}

const mapStateToProps = state => {
    return {
        channels: state.channels
    };
};

const mapDispatchToProps = dispatch => {
    return bindActionCreators(actions, dispatch);
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Navbar);

如何从axios访问此诺言中的对象?

1 个答案:

答案 0 :(得分:1)

您无法在化简器中调用ResumeDialogAsync,因为它是异步函数,并且化简器是同步的。但是,您可以在api响应返回后调度操作

getChannels()

从组件内部调用它并传递调度。

您也可以按照Emile的建议修改现有操作:

export const getChannels = (dispatch) => {
    const token = "token";
    axios
        .get(`https://slack.com/api/conversations.list?token=${token}`)
        .then(response => {
            dispatch(//your action here... )
        });
};