希望你們都做得很好,我已經嘗試尋找有關我在 ReactJS 中遇到的這個問題的具體答案,我正在嘗試映射我通過本地系統獲取的陣列,但我一直在得到這個控制臺中的錯誤:
TypeError: null is not an object (evaluating 'daysData.map')
這是我從 fetch 初始化陣列的部分代碼的快照:

這里是文本格式:
// Here I initalize the array with useState
const [daysData, setDaysData] = useState(null);
// Here is the port I'm fetching my array from.
useEffect(() => {
fetch('http://localhost:5001/chocolates')
.then((resp) => resp.json())
.then((data) => setDaysData(data));
}, []);
// Console logging is sending back the array with no issues
console.log(daysData);
這是我嘗試使用陣列中的“id”鍵渲染 a 的 map 函式:

這是文本格式的代碼:
{/* Here I'm getting the error " TypeError: null is not an object (evaluating 'daysData.map') " */}
{daysData.map((day) => (
<div>{day.id}</div>
))}
這是我嘗試從中獲取資料的陣列示例:

提前感謝您的任何幫助
uj5u.com熱心網友回復:
只需將默認狀態設定為空陣列而不是 null,以便在Array.prototype.map()接收資料之前在初始渲染上作業。
空陣列的 map() 不會在渲染視圖中產生任何東西
const [daysData, setDaysData] = useState([]);
uj5u.com熱心網友回復:
您的陣列在呈現時為空,并且您的 api 在呈現您的 Web 應用程式后獲取,因此您需要像這樣有條件地設定它
{daysData !== null? daysData.map((day) => <div>{day.id}</div>:null)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392460.html
標籤:javascript 数组 反应
