HeatMap 組件回傳一個空白螢屏,在網頁控制臺中出現錯誤。
import React, { useState, useEffect } from "react";
import ClinicalRoom from '../images/ClinicalRoom.jpg'
import data3 from "../data.json"
import green from "../images/green.png"
import red from "../images/red.png"
export default function HeatMapTable({ list, colNames, room, height='auto'}) {
const [count, setCount] = useState(0)
const [backendData, setBackendData] = useState([{}])
colNames = ["", "", "",""]
useEffect(() => {
fetch("/heatmapapi").then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
}, [count] )
list = backendData[count].mapped
room = backendData[count].room
console.log(list)
return (
<div className="theme1">
<h1>Heat Map</h1>
<p1 >Room: {room}</p1>
<button onClick={() => setCount(count - 1)}>Prev</button>
<button onClick={() => setCount(count === 9 ? console.log("no more"): count 1)}>Next</button>
<div className="layer">
{list.length > 0 && (
<table cellSpacing="0" style={{ height: height}}>
<thead>
<tr>
{colNames.map((headerItem, index) => (
<th key={index}>
{headerItem.toUpperCase()}
</th>
))}
</tr>
</thead>
<tbody>
{Object.values(list).map((obj, index) => (
<tr key={index}>
{Object.values(obj).map((value, index2) => (
<td key={index2}>
{value === 0 ? <img className="map"src={green}/> : <img className="map" src={red}/>}
</td>
))}
</tr>
))}
</tbody>
</table>
)}
<img className="room" src={ClinicalRoom}></img>
</div>
</div>
)
}
該組件正在 App.js 中呈現,如下所示:
<Route path ="/heatmap" element={< HeatMap />} />
該組件使用 express 從 server.js 中獲取資料,如下所示:
const data2 = require("../client/src/data.json")
app.get("/heatmapapi", (req, res) => {
res.json(data2)})
data.json 檔案中的資料位于陣列中,如下所示:
{"room": "101",
"mapped":
[{"1":0, "2":1 ,"3":0, "4":1},
{"1":0, "2":0, "3":0, "4":0},
{"1":0, "2":0, "3":0, "4":0},
{"1":0, "2":1, "3":0, "4":0},
{"1":0, "2":0, "3":0, "4":0}],
"staffnum": 1}
我不知道為什么,但如果我執行以下操作,程式運行完美,沒有錯誤:
運行程式
設定串列和房間:
list = backendData room = backendData.room
保存并重繪
設定串列和房間回到:
list = backendData[count].mapped room = backendData[count].room
保存并重繪
uj5u.com熱心網友回復:
這是組件的初始(相關)狀態的表示:
1- backenData = [{}]
2- count = 0
3-list = backendData[count].mapped
從1-,2-我們可以推斷出派生狀態list是undefined。
當您訪問list.lengthieundefined.length時,它??會引發錯誤。要管理list未定義的情況,您可以使用可選的鏈接運算子,如下所示:list?.length
import React, { useState, useEffect } from "react";
...
export default function HeatMapTable({ list, colNames, room, height='auto'}) {
...
return (
...
<div className="layer">
{list?.length > 0 && (
....
)}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/526254.html
標籤:反应json
上一篇:型別'MutableRefObject<HTMLInputElement|undefined>'不可分配給型別'LegacyRef<HTMLInputE
下一篇:Redux中的多個輸入
