【问题标题】:Fetching data with axios in react在反应中使用 axios 获取数据
【发布时间】:2019-08-09 06:25:51
【问题描述】:

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

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

希望有人可以帮助我。

【问题讨论】:

  • 你应该控制台response.data.tracks而不是data来检查来自服务器的数据响应。而{...response.data.tracks} 等于response.data.tracks
  • 谢谢,但现在我得到了未定义的曲目
  • 那么服务器给你的数据没有tracks属性?您应该在发送它之前检查数据响应结构。喜欢console.log(response)

标签: reactjs axios fetch get-request


【解决方案1】:

如果您不使用 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})
    }
}

【讨论】:

  • 我正在使用 redux
  • componentDidMount() 仍然是这样做的好地方,但是使用 redux 你想要做的是集中应用程序的状态并将状态序列化到 componentDidMount 中的 props
  • 我的 body.js 组件中有它,编辑了问题
【解决方案2】:

我注意到“BusRace/GetRacesTrack”是正确的吗?可能不是“BusRace/GetRaceTracks”,您在问题中确实将轨道称为复数。

【讨论】:

  • 获取赛道的方法和他各自的种族,感谢您的观察,问题已经编辑。
【解决方案3】:

除了@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)), [])
}

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 2020-06-28
    • 2020-03-16
    • 1970-01-01
    • 2020-09-24
    • 2018-10-05
    • 2022-11-14
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多