我是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);
}
希望有人可以帮助我。
答案 0 :(得分:0)
我注意到的快速问题是“ BusRace / GetRacesTrack”,对吗?也许不是“ BusRace / GetRaceTracks”,您在问题中确实将轨道称为复数。
答案 1 :(得分:0)
如果您不使用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})
}
}
答案 2 :(得分:0)
除了@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)), [])
}