javascript - 无法解决 redux reducer 函数中的 axios promise

标签 javascript reactjs redux promise

我正在尝试从 slack api 获取 channel 列表并将它们存储在 redux store 中并使用react。

axios 正在获取一个 [[PromiseValue]],但我无法获取其中的对象:

reducer 文件:

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 访问这个 promise 中的对象?

最佳答案

您不能在 reducer 中调用 getChannels(),因为它是一个异步函数,而您的 reducer 是同步的。但是,您可以在 api 响应返回后发送您的操作

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

从您的组件中调用它并传入 dispatch。

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

  export const getChannels = () => dispatch => {
     const token = "token";
     axios
        .get(`https://slack.com/api/conversations.list?token=${token}`)
        .then(response => {
            dispatch({
                 type: actionTypes.GET_CHANNELS, 
                 payload: response.data
               })
        });
    };    
 };

关于javascript - 无法解决 redux reducer 函数中的 axios promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56569474/

相关文章:

reactjs - 如何在 React 应用程序中渲染 React 应用程序(嵌套 React 应用程序)

reactjs - 我应该将组件中定义的所有函数包装在 useCallback 中吗?

javascript - 如何处理多个 api 请求,以显示来自 redux 存储中一个变量的加载指示器

javascript - 在我通过 Redux 传递它的特殊情况下,这个箭头函数如何工作

javascript - 从通过 echo 语句动态添加的表单元素获取 POST 值?

javascript - innerHTML 不接受检索到的变量

javascript - 如何使用 react-redux connect 获取初始数据

typescript - 包括 if else 子句会产生类型错误

javascript - 如何在 HTML、CSS 和 JS 中叠加多个图像?

javascript - 如何在rails link_to 的表单数据中传递查询参数而不是将其附加在url中?