gpt4 book ai didi

javascript - 使用 Axios 处理 Redux 中的 api 调用

转载 作者:行者123 更新时间:2023-12-03 13:02:56 25 4
gpt4 key购买 nike

大家晚上好!

我是 React 和 Redux 的初学者,所以如果这听起来完全愚蠢,请耐心等待。我正在尝试学习如何在 Redux 中执行一些 API 调用,但进展并不顺利。当我控制台记录来自操作创建者的请求时, promise 值始终为“未定义”,因此我不确定我是否正确执行此操作。

我的目标是从有效负载对象内的数据中获取信息并将其显示在组件内。过去几天我一直在努力让它发挥作用,但我完全迷失了。

我正在使用 Axios for 和 redux-promise 来处理调用。

任何帮助将不胜感激。

这是控制台的输出。

enter image description here

enter image description here

Action 创建器

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;
}

组件

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);

最佳答案

axios 是 promise ,因此您需要使用 then 来获取结果。您应该在单独的文件中请求 api,并在结果返回时调用您的操作。

 //WebAPIUtil.js
axios.get('http://localhost:3000/flug')
.then(function(result){
YourAction.getAllFlights(result)
});

您的操作文件将如下所示:

export function getAllFlights(request) {
console.log(request);
return {
type: FETCH_FLIGHT,
payload: request
};
}

关于javascript - 使用 Axios 处理 Redux 中的 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com