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'])
1 Answer
Reset to default 0In 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]);
}
本文标签:
版权声明:本文标题:reactjs - Why does adding a number to a useState array make it non-iterable, but adding a string works? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742377198a2463398.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
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