我是反应新手,所以我尝试使用 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);
EDIT从我的组件 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);
}
希望可以有人帮帮我。
如果您不使用 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})
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)