问题
I'm new in react so I'm trying to make a get request with axios in react with a service to get a track and the respective races from it, but I got track like a empty object. I need to know how to make the get request efficiently.
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 Adding from my component 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);
}
Hope someone can help me.
回答1:
If you are not using Redux or other state management usually a good place to fetch data is componentDidMount()
, so you define your component with it's initial state, once the component is mounted the axios call is made and once the data is resolved you update the state. Something like this.
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:
Quick thing I noticed was "BusRace/GetRacesTrack" is that correct? not maybe "BusRace/GetRaceTracks", you do refer to tracks as plural in your question.
回答3:
In addition to @Dupocas answer you can also use a functional component for this:
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)), [])
}
来源:https://stackoverflow.com/questions/55228930/fetching-data-with-axios-in-react