在反应中使用axios获取数据

Fetching data with axios in react

我是 React 的新手,所以我正在尝试使用 axios 发出获取请求以与服务做出反应以从中获取赛道和相应的比赛,但我得到的赛道就像一个空对象。我需要知道如何有效地发出获取请求。

trackUtils.js

import AppDispatcher from '../dispatcher/AppDispatcher';
import ActionTypes from '../constants/AppConstants';
import config from '../../config';
import axios from 'axios';

class trackUtil {

    constructor() {
        this.serverConfig = config.ServiceConfig;
        this.baseURL = this.serverConfig.url + ':' + this.serverConfig.port + '/';
        this.appConfig = config.AppConfig;
    }

    trackRequest(data) {
        const url = this.baseURL + 'BusRace/GetRacesTrack';

        axios.get(url)
            .then((response ) =>  {
                AppDispatcher.dispatch({
                    type: ActionTypes.GET_TRACK,
                    data: { ...response.data.tracks }
                });
                console.log(data);
            })
            .catch((error) => {
                console.log(error);
            });
    };

}

export default new trackUtil();

ConfigStore.js

import { ReduceStore } from 'flux/utils';
import ActionTypes from '../constants/AppConstants';
import AppDispatcher from '../dispatcher/AppDispatcher';
import config from '../../config';


class ConfigStore extends ReduceStore {

    getInitialState() {
        return {
            language: config.SiteConfig.defaultLanguage,
            languageLabels: {},
            tracks : {}

        };
    }

    reduce(state, action) {

        switch (action.type) {
            case ActionTypes.GET_TRACK:
                var newState = Object.assign({}, state);
                newState.tracks = action.data;
                return newState;
            default:
                return state;
        }
    }
}

export default new ConfigStore(AppDispatcher);

编辑 从我的组件添加 Body.js

static getStores() {
    return [ConfigStore];
};

static calculateState() {
    let configData = ConfigStore.getState();
    return {
        configInfo: configData,
        local: {"lineTypesDropTitle": ""}
    };
};

componentDidMount() {

    const params = {...this.state, ...{actionType: ActionTypes.GET_TRACK}};
    ActionCreators.actionTrigger(params);
}

希望有人能帮助我。

我很快注意到 "BusRace/GetRacesTrack" 对吗?可能不是 "BusRace/GetRaceTracks",你确实在你的问题中将曲目称为复数。

如果您不使用 Redux 或其他状态管理,通常获取数据的好地方是 componentDidMount(),因此您可以使用它的初始状态定义您的组件,一旦组件被安装,就会进行 axios 调用并且一旦数据被解析,你就更新状态。像这样。

class MyAwesomeComponent extends Component{
    //Defining initial state
    state ={
        data : null
    }

    //Making the API call and once resolved updating the state
    componentDidMount(){
        axios.get('myendpoint').then( res => this.setState({data : res})
    }
}

除了@Dupocas 的回答之外,您还可以为此使用功能组件:

const MyAwesomeComponent = () => {
    //Defining initial state
    const [data, setData] = useState(null)

    //Making the API call and once resolved updating the state
    useEffect(() => axios.get('myendpoint').then( res => setData(res)), [])
}