【问题标题】:React/API/Chart.js: Expected an assignment or function call and instead saw an expressionReact/API/Chart.js:期望一个赋值或函数调用,而是看到一个表达式
【发布时间】: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


【解决方案1】:

感谢您的帮助,该解决方案不起作用,但我在下面找到了一个可以运行代码 sn-p 的解决方案。

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 [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.
      })
      .catch((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;

但是现在我发现它正在屏幕上显示“错误:无法读取未定义的属性'数据'”的错误,所以我认为我的 api 数据可能没有被正确解析但无法弄清楚原因

【讨论】:

    【解决方案2】:

    试试这个。

    useEffect(() => {
    
    let Fore = [];
    let Act = [];
    
    fetch('https://api.carbonintensity.org.uk/intensity/2020-09-01T15:30Z/2020-09-10T17:00Z')
      .then(res => res.json())
      .then(data => {
        for (const dataObj of data.data) {
        Fore.push(parseInt(dataObj.intensity.forecast));
        Act.push(parseInt(dataObj.intensity.actual));
       }
       setIsLoaded(true);
      })
      .catch((error) => {
        setIsLoaded(true);
        setChartData({
          labels: Fore,
          datasets: [
           {
            label: "Carbon Intensity Levels",
            data: Act,
            backgroundColor: "#F58A07",
            borderWidth: 4
           }
          ]
        });
       setError(error);
     })
    }, [])
    
    

    【讨论】:

    • 谢谢,我已经实现了这个,它消除了一个错误,但现在错误显示“错误:res.data.data 不可迭代”所以我现在会尝试解决这个问题
    • 尝试在第二次使用这个回调 then( (({data}) => { data.forEach(dataObj => { Fore.push(parseInt(dataObj.intensity.forecast)); Act. push(parseInt(dataObj.intensity.actual)); }); setIsLoaded(true) }))
    • 没用,但通过在最后放置一个 .finally 并在其中设置 setIsLoaded(true) 解决了它
    猜你喜欢
    • 2020-02-12
    • 2019-10-15
    • 1970-01-01
    • 2021-04-12
    • 2022-01-14
    • 2017-09-09
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多