Javascript Can';在redux reducer函数中解析axios承诺
我试图从SlackAPI中获取通道列表,并将它们存储在redux存储中,然后做出反应 axios正在获取一个[[PromiseValue]],我无法获取其中的对象: 减速器文件:Javascript Can';在redux reducer函数中解析axios承诺,javascript,reactjs,redux,promise,Javascript,Reactjs,Redux,Promise,我试图从SlackAPI中获取通道列表,并将它们存储在redux存储中,然后做出反应 axios正在获取一个[[PromiseValue]],我无法获取其中的对象: 减速器文件: import * as actionTypes from "../actions/types"; import { getChannels } from "./../services/channelService"; const channelsReducer = (state = getChannels(), ac
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访问此承诺中的对象?您不能在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... )
});
};
从组件内部调用此函数并传入分派
您也可以按照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
})
});
};
};
我不想弄脏我的部件。我必须这么做吗?不,如果你使用redux的话就不需要了。您可以在任何地方触发通道获取,并发送一个操作将其弹出到存储中,然后通过
connect()
将其放入组件中。我现在正在执行此操作。在codeah cool中重新检查我的组件部分,在这种情况下,您可以随意触发api调用(但是你需要通过dispatch访问商店,所以在你的
@Afshin中的某个地方,方法是在你的操作中,我看到你已经在使用thunk操作,所以这将是从你的通道服务文件在getChannels
操作中调用getChannels
函数的问题。因此,您的操作保持超级简单,将抓取逻辑隔离到您的服务文件中,就像您现在所做的那样。