I'm trying to use react hooks in my project and I have a problem with useState when I use array as value.
const List = () => {
const [list, setList] = useState({ name: ["Bob", "Alice", "Dora"] })
const reverseList = () => {
setList({ name: list.name.reverse() })
}
return (
<div>
<button onClick={reverseList}>Reverse</button>
{list.name.map(name => name)}
</div>
)
}
above code works fine. but...
const List = () => {
const [list, setList] = useState(["Bob", "Alice", "Dora"])
const reverseList = () => {
setList(list.name.reverse())
}
return (
<div>
<button onClick={reverseList}>Reverse</button>
{list.map(name => name)}
</div>
)
}
It doesn't work?! Can you please tell me why React works like this and what's the difference between the above codes?
In the first instance, you are setting state to a new object reference. In the second case, you are not setting a new object reference, you're calling reverse
on the array, which mutates it .
In both cases, I would recommend making a shallow copy of the array and calling reverse
so React knows that it's dealing with new state and therefore knows to re-render.
const List = () => {
const [list, setList] = useState({ name: ["Bob", "Alice", "Dora"] })
const reverseList = () => {
// Shallow copy
setList({ name: [...list.name].reverse() })
}
return (
<div>
<button onClick={reverseList}>Reverse</button>
{list.name.map(name => name)}
</div>
)
}
const List = () => {
const [list, setList] = useState(["Bob", "Alice", "Dora"])
const reverseList = () => {
// Shallow copy
setList([...list.name].reverse())
}
return (
<div>
<button onClick={reverseList}>Reverse</button>
{list.map(name => name)}
</div>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.