reactjs 用Axios从C#控制器中提取JSON字符串到React页面

jhiyze9q  于 2023-01-12  发布在  React
关注(0)|答案(2)|浏览(130)

我尝试创建一个由4个对象组成的JSON字符串,并将其从C#控制器发送到Axios的React函数,然后将数据放入div的类名中,以便根据它们是否处于活动状态来更改它们的样式。使用我的代码时,我遇到了UncaughtTypeError:无法读取null的属性(阅读“0”)。我认为数据没有到达函数,但我不确定原因。代码如下:
js(我尝试在其中设置类名的值)

import React, { useState, useEffect } from 'react';
import axios from "axios";

function ServerStatuses() {
    const [serverCycleData, setServerCycleData] = useState(null);

    useEffect(() => {
        //sets the interval for the serverCycle data to be sent over every 2 seconds
        const serverCycleData = () => {
            axios.get("/serverCycle")
                .then(res => {
                    setServerCycleData(res.data);
                })
        }
        serverCycleData();
        const interval = setInterval(() => {
            serverCycleData()
        }, 50000);
        return () => clearInterval(interval);
    }, []);

        return (
            <div id="statuses">
                <div id="LWStatus" className={serverCycleData[0].className}>SERVER</div>
                <div id="CONAStatus" class={serverCycleData[1].className}>CONA</div>
                <div id="PDAStatus" class={serverCycleData[2].className}>PDA</div>
                <div id="OverallStatus" class={serverCycleData[3].className}>ERROR</div>
            </div>
        )
    };

export default ServerStatuses;

cs(第一个是我的API调用)

[HttpGet]
        [Route("/hGrabLocation")]
        public string GrabLocation()
        {
            var plantLocation = "LOCATION HERE";
            //using the object here to pull the data
            if (ObjSiteConfiguration.Initialized)
            {
                plantLocation = ObjSiteConfiguration.Palletizers[0].PlantName;
            }
            else
            {
                plantLocation = "Site not initialized";
            }

            return plantLocation;

        }

ProductionController.cs(这只是我在开始时创建的列表,用于在中存储和提取值)

private List<ObjServerStatus> serverStatuses = new()
        {
                new ObjServerStatus{serverType = "LW", serverStatus = false, statusClass = "header-icon_error"},
                new ObjServerStatus{serverType = "CONA", serverStatus = false, statusClass = "header-icon_error"},
                new ObjServerStatus{serverType = "PDA", serverStatus = false, statusClass = "header-icon_error"},
                new ObjServerStatus{serverType = "OVERALL", serverStatus = false, statusClass = "header-icon_error"}
            };

我试图运行该网站,并不断得到一个未捕获的TypeError:无法读取null的属性(阅读“0”)。我希望加载标头,并且div标记将加载并附加正确的类。

2cmtqfgy

2cmtqfgy1#

serverCycleData最初是null,在响应加载之前
或者添加一条early return语句

function ServerStatuses() {
  const [serverCycleData, setServerCycleData] = useState(null);

  useEffect(() => {
    //sets the interval for the serverCycle data to be sent over every 2 seconds
    const serverCycleData = () => {
      axios.get("/serverCycle").then((res) => {
        setServerCycleData(res.data);
      });
    };
    serverCycleData();
    const interval = setInterval(() => {
      serverCycleData();
    }, 50000);
    return () => clearInterval(interval);
  }, []);

  if (!serverCycleData) return null

  return (
    <div id="statuses">
      <div id="LWStatus" className={serverCycleData[0].className}>
        SERVER
      </div>
      <div id="CONAStatus" class={serverCycleData[1].className}>
        CONA
      </div>
      <div id="PDAStatus" class={serverCycleData[2].className}>
        PDA
      </div>
      <div id="OverallStatus" class={serverCycleData[3].className}>
        ERROR
      </div>
    </div>
  );
}

或使用可选链接

function ServerStatuses() {
  const [serverCycleData, setServerCycleData] = useState(null);

  useEffect(() => {
    //sets the interval for the serverCycle data to be sent over every 2 seconds
    const serverCycleData = () => {
      axios.get("/serverCycle").then((res) => {
        setServerCycleData(res.data);
      });
    };
    serverCycleData();
    const interval = setInterval(() => {
      serverCycleData();
    }, 50000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div id="statuses">
      <div id="LWStatus" className={serverCycleData?.[0].className}>
        SERVER
      </div>
      <div id="CONAStatus" class={serverCycleData?.[1].className}>
        CONA
      </div>
      <div id="PDAStatus" class={serverCycleData?.[2].className}>
        PDA
      </div>
      <div id="OverallStatus" class={serverCycleData?.[3].className}>
        ERROR
      </div>
    </div>
  );
}
rsl1atfo

rsl1atfo2#

React在每次“determines it needs to“时运行ServerStatus块。其中一次将是useEffect运行之前的第一次通过。
在那一刻

const [serverCycleData, setServerCycleData] = useState(null);

表示serverCycleData的useEffect中的变量为空。
一种选择是使用一个可以遵从的数组进行初始化(即,将服务器的预期状态数组设置为有意义的值,如“waiting for server”)。
这可能类似于:

const [serverCycleData, setServerCycleData] = useState(["header-icon_waiting_for_server","header-icon_waiting_for_server", "header-icon_waiting_for_server", "header-icon_waiting_for_server" ]);

相关问题