[英]How to fix Data.map is not a function in Reactjs?
所以我有一個 Notesdata 數組,其中包含 object 和屬性標題、標語、描述。 Notesdata array is stored in the "data" state variable in the App component and I am sending this data state variable to notes view component to populate on the UI but when I am appending a new object inside the data state variable and then sending it to notesview 組件,我收到錯誤“Data.map 不是函數”。
當我打印“數據”state 變量時,我得到一個數組,但是當我檢查它的類型時,它顯示的是“對象”,我很困惑為什么它會這樣顯示。
我還嘗試在“數據”state 變量上使用 Array.from(),然后再將其傳遞給 notesview,但這也顯示了相同的錯誤。
------------應用組件------
import React, { useState } from "react";
import './App.css';
import Input from './Components/Input';
import Navbar from './Components/Navbar';
import Notesview from './Components/Notesview';
import Notesdata from "./Data/Notesdata";
function App() {
// const [data, setdata] = useState(Notesdata);
const [data, setData] = useState(Notesdata);
function handleDelete(id) {
let newData = data.filter((item) => item.id !== id)
setData(newData)
}
function handlePost(value) {
let newval = data.push(value)
setData(newval)
console.log(typeof data)
console.log(data)
}
return (
<div className="App">
<header className="App-header">
<Navbar />
<Input data={data} handlePost={(value) => handlePost(value)} />
<Notesview handleDelete={handleDelete} Data={data} />
</header>
</div>
);
}
export default App;
-----------------notesview 組件---------------------
import React from 'react'
import Notescard from './Notescard'
import "../Styles/Notes.css"
const Notesview = ({ Data, handleDelete }) => {
return (
<>
<div className='notes'>
{
Data.map((item) => { // here is the Data.map where the error is coming
return <Notescard item={item} handleDelete={handleDelete} />
})
}
</div>
</>
)
}
export default Notesview
您會收到此錯誤,因為 Data 是null
。 您可以在嘗試在 Notesview 中對其進行Notesview
之前檢查Data
的存在,如下所示:
Data && Data.map(...)
這里有很多錯誤:
let newval = data.push(value)
setData(newval)
console.log(typeof data)
console.log(data)
Array.prototype.push
返回數組的長度,因此您將data
設置為number 。 (順便說一下,它沒有.map()
function。)data
)之前對其進行變異。 只需更新它。要正確更新 state,您需要執行以下操作:
setData([...data, value]);
If you might have a batch of updates and you want each state update to use the updating state in the batch rather than the current state in the render, you could use the callback version of the state setter:
setData(d => [...d, value]);
這將創建一個新的數組引用,其中包括data
數組中的所有元素以及新的value
元素,並將該引用設置為更新的 state。 不改變當前渲染的當前 state。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.