【发布时间】:2020-12-18 10:46:32
【问题描述】:
我正在关注此处的文档 (https://reactjs.org/docs/faq-ajax.html),以便 AJAX 和 API 能够获取我的 API 数据,在加载时显示加载微调器,然后在加载后显示图表。
然而,我得到了这个错误:第 31:7 行:期望一个赋值或函数调用,而是看到一个表达式。代码如下:
Chart3.js
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import * as ReactBootStrap from 'react-bootstrap';
import axios from "axios";
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
const [chartData, setChartData] = useState({});
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
let Fore = [];
let Act = [];
fetch('https://api.carbonintensity.org.uk/intensity/2020-09-01T15:30Z/2020-09-10T17:00Z')
.then(res => {
console.log(res);
for (const dataObj of res.data.data) {
Fore.push(parseInt(dataObj.intensity.forecast));
Act.push(parseInt(dataObj.intensity.actual));
setIsLoaded(true);
}
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setChartData({
labels: Fore,
datasets: [
{
label: "Carbon Intensity Levels",
data: Act,
backgroundColor: "#F58A07",
borderWidth: 4
}
]
});
setError(error);
}})
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div> <ReactBootStrap.Spinner animation="border"/> </div>;
} else {
return (
<div className="App">
<h1></h1>
<div className="chart">
<Line
data={chartData}
options={{
responsive: true,
title: { text: "2020-09-01T15:30Z - 2020-09-10T17:00Z", display: true },
scales: {
yAxes: [
{
ticks: {
autoSkip: true,
maxTicksLimit: 100,
beginAtZero: true
},
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: "Actual"
}
}
],
xAxes: [
{
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: "Forecast"
}
}
]
}
}} />
</div>
</div>
);
}
}
export default MyComponent;
它说错误在第 31 行,这是代码“(error) => {...”的一部分
【问题讨论】:
-
您的 fetch 语法不正确。将其与您链接的示例进行比较。
标签: javascript reactjs api error-handling