簡體   English   中英

如何修復 Data.map 不是 Reactjs 中的 function?

[英]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,但這也顯示了相同的錯誤。

第一個console.log顯示的對象是typeof“data”狀態變量,而在第二行它是數組形式的實際“data”狀態變量

------------應用組件------

   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)
  1. Array.prototype.push返回數組的長度,因此您將data設置為number (順便說一下,它沒有.map() function。)
  2. 您在嘗試更新 state 值( data )之前對其進行變異。 只需更新它。
  3. 您正在嘗試在更新后檢查該值,但您正在檢查當前值而不是值。 State 更新是異步的。

要正確更新 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM