Javascript 如何在React中操作api调用中的数据?
我对openWeatherapi进行了api调用,但问题是数据在解决之前是“未定义的”。因此,当我在ComponentDidMount中调用api并将数据设置为状态时,状态在数据进入之前有一段时间是未定义的。问题是,在此期间,如果我试图用我得到的数据做任何事情,我无法“做一些”未定义的适当的事情,整个事情就会崩溃。我该怎么做 我有一个weatherwidget,我想通过api调用传递天气数据。城市名称包括大陆,因此如果我想对其执行.split(),我会得到一个错误,因为该值最初未定义 这是仪表盘代码Javascript 如何在React中操作api调用中的数据?,javascript,node.js,reactjs,redux,axios,Javascript,Node.js,Reactjs,Redux,Axios,我对openWeatherapi进行了api调用,但问题是数据在解决之前是“未定义的”。因此,当我在ComponentDidMount中调用api并将数据设置为状态时,状态在数据进入之前有一段时间是未定义的。问题是,在此期间,如果我试图用我得到的数据做任何事情,我无法“做一些”未定义的适当的事情,整个事情就会崩溃。我该怎么做 我有一个weatherwidget,我想通过api调用传递天气数据。城市名称包括大陆,因此如果我想对其执行.split(),我会得到一个错误,因为该值最初未定义 这是仪表盘
import React, { PureComponent } from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';
import brand from 'dan-api/dummy/brand';
import { Helmet } from 'react-helmet';
import { withStyles } from '@material-ui/core/styles';
import Hidden from '@material-ui/core/Hidden';
import Grid from '@material-ui/core/Grid';
import moment from 'moment';
import Divider from '@material-ui/core/Divider';
import {
SliderWidget,
CounterIconsWidget,
PerformanceChartWidget,
DateWidget,
TaskWidget,
WeatherWidget,
ContactWidget,
TimelineWidget,
FilesWidget,
} from 'dan-components';
import ScrollableTabs from '../UiElements/demos/Tabs/ScrollTabs';
import styles from './dashboard-jss';
class PersonalDashboard extends PureComponent {
constructor(props) {
super(props);
this.state = {
scheduleToday: [],
scheduleTomorrow: [],
weather: {},
};
}
fetchTodaySchedule = () => {
axios
.get(`/api/total/schedule/?day=${moment().format('llll')}`)
.then(response => {
this.setState({
scheduleToday: response.data[0].result,
});
})
.catch(error => {
console.log(error);
});
};
fetchTomorrowSchedule = () => {
axios
.get(
`api/total/schedule/?day=${moment()
.add(1, 'days')
.format('llll')}`,
)
.then(response => {
this.setState({
scheduleTomorrow: response.data[0].result,
});
})
.catch(error => {
console.log(error);
});
};
fetchWeather = async () => {
axios
.get(`api/total/weather`)
.then(response => {
this.setState({
weather: response.data,
});
})
.catch(error => {
console.log(error);
});
};
async componentWillMount() {
await this.fetchWeather();
this.fetchTodaySchedule();
this.fetchTomorrowSchedule();
}
render() {
const title = brand.name + ' - Personal Dashboard';
const description = brand.desc;
const { classes } = this.props;
return (
<div>
<Helmet>
<title>{title}</title>
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
</Helmet>
{/* 1st Section */}
<Grid container spacing={3} className={classes.root}>
<Grid item md={6} xs={12}>
<CounterIconsWidget />
</Grid>
<Grid item md={6} sm={12} xs={12}>
<div className={classes.sliderWrap}>
<SliderWidget />
</div>
</Grid>
</Grid>
<Divider className={classes.divider} />
{/* 2nd Section */}
<Grid container spacing={2} className={classes.root}>
<Grid item xs={12}>
<PerformanceChartWidget />
</Grid>
</Grid>
{/* 3rd Section */}
<Grid container spacing={3} className={classes.root}>
<Grid item md={6} xs={12}>
<Divider className={classes.divider} />
{/* <ScrollableTabs /> */}
<ContactWidget />
<Divider className={classes.divider} />
<TaskWidget />
</Grid>
<Grid item md={6} xs={12}>
<Hidden mdDown>
<Divider className={classes.divider} />
</Hidden>
<WeatherWidget weatherData={this.state.weather} />
<Divider className={classes.divider} />
<DateWidget />
<Divider className={classes.divider} />
<TimelineWidget />
</Grid>
</Grid>
<Divider className={classes.divider} />
<FilesWidget />
</div>
);
}
}
PersonalDashboard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(PersonalDashboard);
import React,{PureComponent}来自'React';
从“axios”导入axios;
从“道具类型”导入道具类型;
从“dan api/假人/品牌”进口品牌;
从“react Helmet”导入{Helmet};
从“@material ui/core/styles”导入{withStyles}”;
从“@material ui/core/Hidden”导入隐藏项;
从“@material ui/core/Grid”导入网格;
从“力矩”中导入力矩;
从“@material ui/core/Divider”导入分隔器;
进口{
滑杆,
反图标控件,
PerformanceChartWidget,
DateWidget,
TaskWidget,
WeatherWidget,
ContactWidget,
TimelineWidget,
文件小部件,
}来自“dan组件”;
从“../UiElements/demos/Tabs/ScrollTabs”导入可滚动选项卡;
从“/dashboard jss”导入样式;
类PersonalDashboard扩展了PureComponent{
建造师(道具){
超级(道具);
此.state={
今天的日程安排:[],
明天的日程安排:[],
天气:{},
};
}
fetchTodaySchedule=()=>{
axios
.get(`/api/total/schedule/?day=${moment().format('llll')}`)
。然后(响应=>{
这是我的国家({
scheduleToday:响应。数据[0]。结果,
});
})
.catch(错误=>{
console.log(错误);
});
};
fetchTomorrowSchedule=()=>{
axios
.得到(
`api/total/schedule/?day=${moment()
.添加(1,‘天’)
.format('llll')}`,
)
。然后(响应=>{
这是我的国家({
ScheduleMother:响应。数据[0]。结果,
});
})
.catch(错误=>{
console.log(错误);
});
};
fetchWeather=async()=>{
axios
.get(`api/total/weather`)
。然后(响应=>{
这是我的国家({
天气:响应数据,
});
})
.catch(错误=>{
console.log(错误);
});
};
异步组件willmount(){
等待这个;
此.fetchTodaySchedule();
这是.fetchTomorrowSchedule();
}
render(){
const title=brand.name+“-个人仪表板”;
const description=brand.desc;
const{classes}=this.props;
返回(
{title}
{/*第1节*/}
{/*第二节*/}
{/*第三节*/}
{/* */}
);
}
}
PersonalDashboard.propTypes={
类:PropTypes.object.isRequired,
};
导出默认样式(样式)(PersonalDashboard);
这是weatherwidget组件
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import 'dan-styles/vendors/react-weather/GenericWeather.css';
import classNames from 'classnames';
import styles from './widget-jss';
function WeatherWidget(props) {
const { status, classes, temp, city, weatherData } = props;
const cls = classNames('weather-icon', status);
const bg = classNames(classes.weathercard, status === 'sun' ? classes.sun : classes.cloud);
return (
<div className={bg}>
<div className="wheater-wrap">
<div className={cls} />
<h1>{temp}º</h1>
<p>{weatherData.timezone}</p>
</div>
</div>
);
}
WeatherWidget.propTypes = {
classes: PropTypes.object.isRequired,
city: PropTypes.string,
temp: PropTypes.number,
status: PropTypes.string,
};
WeatherWidget.defaultProps = {
city: 'Bucharest',
temp: 28,
status: 'sun', // cloud and sun
};
export default withStyles(styles)(WeatherWidget);
从“React”导入React;
从“道具类型”导入道具类型;
从“@material ui/core/styles”导入{withStyles}”;
导入'dan styles/vendors/react weather/GenericWeather.css';
从“类名称”导入类名称;
从“/widget jss”导入样式;
功能WeatherWidget(道具){
const{status,classes,temp,city,weatherData}=props;
const cls=类名(“天气图标”,状态);
const bg=classNames(classes.weathercard,status=='sun'?classes.sun:classes.cloud);
返回(
{temp}º
{weatherData.timezone}
);
}
WeatherWidget.propTypes={
类:PropTypes.object.isRequired,
城市:PropTypes.string,
temp:PropTypes.number,
状态:PropTypes.string,
};
WeatherWidget.defaultProps={
城市:“布加勒斯特”,
温度:28,
状态:'太阳',//云和太阳
};
导出默认样式(样式)(WeatherWidget);
我最终就是这样做的,并使用了异步组件didmount 到目前为止,它似乎运作良好
async componentDidMount() {
const ticketsPromise = await axios.get('api/total/tickets');
const alertsPromise = await axios.get('api/total/alerts');
const callsPromise = await axios.get('api/total/avaya/logs');
const weatherPromise = await axios.get('api/total/weather');
const scheduleTodayPromise = await axios.get(`/api/total/schedule/?day=${today}`);
const scheduleTomorrowPromise = await axios.get(`/api/total/schedule/?day=${tomorrow}`);
const resolves = await Promise.all([
ticketsPromise.data,
alertsPromise.data,
callsPromise.data,
weatherPromise.data,
scheduleTodayPromise.data[0].result,
scheduleTomorrowPromise.data[0].result,
]);
const [ticketsData, alertsData, callsData, weatherData, schedTodayData, schedTomorrowData] =
resolves || [];
this.setState({ tickets: ticketsData.tickets });
this.setState({ alerts: alertsData });
this.setState({ calls: callsData });
this.setState({ weather: weatherData });
this.setState({ scheduleToday: schedTodayData });
this.setState({ scheduleTomorrow: schedTomorrowData });
}
异步组件didmount(){
试一试{
const[门票、警报、电话、天气、计划今天、计划明天]=等待承诺。全部([
axios.get('api/total/tickets'),
axios.get('api/total/alerts'),
axios.get('api/total/avaya/logs'),
axios.get('api/total/weather'),
get(`/api/total/schedule/?day=${today}`),
get(`/api/total/schedule/?day=${明天}`),
]);
这是我的国家({
票证:票证,数据,票证,
警报:警报。数据,
calls:calls.data,
天气:weather.data,
scheduleToday:schedToday.data[0]。结果,
scheduleTomorrow:scheduleTomorrow.data[0]。结果
});
}捕捉(错误){
控制台错误(err);
}
}
你做得不对。您不需要使用Promise.all,因为ticketsPromise.data不是承诺。ticketsPromise已不是承诺,因为它由
wait