[英]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;
tmp
state 是 object,但是您嘗試將其變異為數組useEffect
掛鈎並更新 statearray.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.