簡體   English   中英

無法插入數組 reactjs

[英]Can't insert into array reactjs

我是 reactjs 的初學者,我正在嘗試 map 一個數組並獲取文件並設置到另一個數組中,但是我收到一個錯誤“TypeError:tmp.book is not iterable”。

這是我的代碼

import "./App.css";
import { useState } from "react";

function App() {
  const array = [
    {
      no: "3",
      title: "dream",
      singer: "anak",
    },
    {
      no: "4",
      title: "dream",
      singer: "anak",
    },
  ];
  const [tmp, setTmp] = useState({
    food: [
      {
        name: "banana",
        color: "yellow",
        quality: "good",
      },
      {
        name: "apple",
        color: "red",
        quality: "bad",
      },
    ],
    book: [
      {
        no: "1",
        title: "dream",
        singer: "anak",
      },
      {
        no: "2",
        title: "jack",
        singer: "lome",
      },
    ],
  });

  array.map((item) => {
    setTmp([
      ...tmp.book,
      {
        no: item.no,
        title: item.title,
        singer: item.singer,
      },
    ]);
  });

  return "";
}

export default App;

這是結果

有人可以向我解釋為什么我會收到錯誤以及如何解決它嗎? 希望你們明白我在問什么:D

tmp是 object,但您正在嘗試使用數組值設置 Tmp。

import "./App.css";
import {
  useState
} from "react";

function App() {
  ...
  useEffect(() => { // iterate `array` inside useEffect
    array.map((item) => {
      const cloned = { ...tmp };
      cloned.book.push({
          no: item.no,
          title: item.title,
          singer: item.singer,
      });
      setTmp(cloned); // set object value since it is set as an object initially
    });
  }, []);

  return "";
}

export default App;

問題

  1. 映射但不返回或保存任何映射值
  2. tmp state 是 object,但是您嘗試將其變異為數組
  3. 組件主體中的 State 更新將觸發無限渲染循環

解決方案

  1. 使用useEffect掛鈎並更新 state
  2. 在使用循環時,使用功能 state 更新以正確地從以前的 state 更新
  3. 如果沒有實際映射數據,請使用array.prototype.forEach

代碼

React.useEffect(() => {
  array.forEach((item) => {
    setTmp((prev) => ({
      ...prev, // <-- copy all existing state
      book: [ // <-- copy state being updated
        ...prev.book,
        {
          no: item.no,
          title: item.title,
          singer: item.singer
        }
      ]
    }));
  });
}, []);

由於array元素 object 的形狀已經與tmp.book數組元素的形狀匹配,您可以簡單地連接兩個 arrays 而無需循環。

React.useEffect(() => {
  setTmp((prev) => ({
    ...prev,
    book: [...prev.book, ...array]
  }));
}, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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