我有一個從站點獲取資料并嘗試獲取其密鑰的組件。
問題是它第一次作業正常,但是當我重繪 頁面/在 VSCode 中保存專案(并且專案自動重繪 )時,它顯示以下錯誤訊息:
TypeError: Cannot convert undefined or null to object
14 | )
15 |
16 | return (
> 17 | <div className="rates">
| ^ 18 | {Object.keys(rates.rates).map(
19 | rate => <Button variant="outlined">
20 | {rate}
代碼(特定組件):
import React, { useState, useEffect } from 'react'
import Button from '@mui/material/Button';
const RatesCard = () => {
const [rates, setRates] = useState([]);
useEffect(
()=>{
fetch("https://api.vatcomply.com/rates")
.then(ratesResponse => ratesResponse.json())
.then(rates => setRates(rates));
}
,[])
return (
<div className="rates">
{Object.keys(rates.rates).map(
rate => <Button variant="outlined">
{rate}
</Button>
)}
</div>
)
}
export default RatesCard
我不知道為什么它第一次起作用,然后就不起作用了。我的猜測是useEffect由于[]依賴關系,鉤子只運行一次,然后當我們重繪 時它說“沒有任何變化,所以我不會運行該函式”因此我們不獲取任何東西,因此rates是undefined......
我不知道為什么會這樣,我只能猜測。我將感謝您的幫助!謝謝!
uj5u.com熱心網友回復:
您的 rate 的默認值應該是一個空物件,其rates屬性設定為空陣列 ( {rates: []})。
通過說以下內容,Object.keys(rates.rates).map您將假設rates將是一個物件,并且rates.rates將是一個陣列。
由于熱重新加載的作業方式,它在“第一次”作業,因為當您保存檔案時,它會將代碼注入瀏覽器而不是重新安裝整個應用程式。因此,您的應用程式將從之前停止的地方繼續運行,即使它在上一次加載時崩潰了。
將您的狀態定義更改為以下內容: const [rates, setRates] = useState({rates:[]});
這將確保當您的應用程式嘗試運行時Object.keys(rates.rates).map它不會崩潰,因為您有一個要迭代的陣列 not null/undefined
uj5u.com熱心網友回復:
useEffect在您的組件安裝后運行,這意味著rates它只是一個沒有名為的屬性的空陣列rates
Object.keys(rates.rates)
嘗試使用
const [rates, setRates] = useState({rates:[]});
或制作一個加載指示器,例如
const RatesCard = () => {
const [rates, setRates] = useState([]);
useEffect(
()=>{
fetch("https://api.vatcomply.com/rates")
.then(ratesResponse => ratesResponse.json())
.then(rates => setRates(rates));
}
,[])
if(rates.length === 0) {
return <h1> loading </hi>
}
return (
<div className="rates">
{Object.keys(rates.rates).map(
rate => <Button variant="outlined">
{rate}
</Button>
)}
</div>
)
uj5u.com熱心網友回復:
首先,您的狀態等于[]在您嘗試執行以下操作的第一次渲染中:Object.keys([].rates)并且顯然這里rates不存在Array它最終Object.keys(undefined)會導致錯誤的結果。
所以我的解決方案不是將整個物件設定為rates您可以通過解構來設定回應的rates物件(參見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/運算子/Destructuring_assignment#object_destructuring):
useEffect(() => {
fetch('https://api.vatcomply.com/rates')
.then((ratesResponse) => ratesResponse.json())
.then(({ rates }) => setRates(rates));
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318254.html
標籤:javascript 反应 材质-ui
