admin管理员组

文章数量:1336380

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]);
}

本文标签: