晚上好大家!
我是React和Redux的初学者,所以如果听起来完全愚蠢的话,请耐心等待 . 我正在尝试学习如何在Redux中执行一些API调用,但这并不是很好 . 当我控制记录来自动作创建者的请求时,promise值总是“未定义”,因此我不确定我是否正确执行此操作 .
我的目标是从有效负载对象内的数据中获取信息并将其显示在组件内 . 过去几天我一直试图让这个工作起来,我完全迷失了 .
我正在使用Axios和redux-promise来处理呼叫 .
任何帮助将不胜感激 .
这是控制台的输出 .
Action Creator
import axios from 'axios';
export const FETCH_FLIGHT = 'FETCH_FLIGHT';
export function getAllFlights() {
const request = axios.get('http://localhost:3000/flug');
console.log(request);
return {
type: FETCH_FLIGHT,
payload: request
};
}
Reducer
import { FETCH_FLIGHT } from '../actions/index';
export default function(state = [], action) {
switch (action.type) {
case FETCH_FLIGHT:
console.log(action)
return [ action.payload.data, ...state ]
}
return state;
}
Component
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getAllFlights } from '../actions/index';
import Destinations from './Destinations';
class App extends Component {
componentWillMount(){
this.props.selectFlight();
}
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
</div>
);
}
function mapStateToProps(state) {
return {
dest: state.icelandair
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ selectFlight: getAllFlights }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
5 回答
axios
是承诺,所以你需要使用then
来获得你的结果 . 您应该在单独的文件中请求您的api,并在结果返回时调用您的操作 .在你的动作文件中将是这样的:
解决此问题的最佳方法是添加redux中间件http://redux.js.org/docs/advanced/Middleware.html以处理所有api请求 .
https://github.com/svrcekmichal/redux-axios-middleware是一个可以使用的即插即用中间件 .
你可以用thunk做到这一点 . https://github.com/gaearon/redux-thunk
你可以在
then
中调度一个动作,它会在从axios调用中得到响应时更新状态 .我照顾这个任务是这样的:
我也认为最好的方法是使用redux-axios-middleware . 设置可能有点棘手,因为您的商店应以类似的方式配置:
而你的动作创建者现在看起来像这样: