最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Why does adding a number to a useState array make it non-iterable, but adding a string works? - Stack Overflow

programmeradmin1浏览0评论

I have a React component where I'm using the useState hook to manage an array. Initially, my state is defined like this: const [rows, setRows] = useState([1]); When I try to append a number to the array using a button click: setRows([...rows, 1]) and iterate through the rows: rows.map((row) => console.log(row)); I encounter an error: TypeError: rows is not iterable.

However, if I append a string instead of a number, for example:

setRows([...rows, 'a'])

I have a React component where I'm using the useState hook to manage an array. Initially, my state is defined like this: const [rows, setRows] = useState([1]); When I try to append a number to the array using a button click: setRows([...rows, 1]) and iterate through the rows: rows.map((row) => console.log(row)); I encounter an error: TypeError: rows is not iterable.

However, if I append a string instead of a number, for example:

setRows([...rows, 'a'])

Share Improve this question asked Nov 20, 2024 at 6:26 preetipreeti 11 bronze badge 2
  • Do: console.log(typeof rows);' console.log(Array.isArray(rows)); console.log(rows); after definition and right before map. If it have changed, it means you are modifying it somewhere else somehow. Strings are iterables (it iterates through the characters), numbers are not. – Flash Thunder Commented Nov 20, 2024 at 6:31
  • I can't replicate this issue. Its working for me. Can you share the code you are using. – Anubhav Sharma Commented Nov 20, 2024 at 6:47
Add a comment  | 

1 Answer 1

Reset to default 0

In react ,when using usestate hook for managing arrays, you typically want to update the sate in an immutable way. This means you should create a new array that includes the existing elements along with the new element you want to add. The issue you are having with adding a number to usestate array making if 'non-iterable'.

Correct Way When you want to add an element to an array in state, you should use spread operator(...).

Example

const [myArray,setMyArray] = useState([]);
//Adding a number
const addNumber = () => {
    setMyArray(prevArray=>[...prevArray,number]);
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论