我正在尝试从 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/