admin管理员组文章数量:1415467
I'm trying to use react hooks in my project and I have a problem with useState when I use array as value.
As you can see in my code below, when I display zoneItems
that it should be like items
array I get an empty array all the time. Would you have an explanation why?
When I use an object instead of array it works
const ShippingCostZone = ({ zone, datas, selectedProducts, getProductById }) => {
const items = datas.items.filter(item => item.zoneId === zone.id)
console.log('========> items', items) // ---- SHOW the good values
const [zoneItems, updateItems] = useState(items)
console.log('========> zoneItems ', zoneItems) // ---- SHOW all the time []
.........
Thanks in advance
I'm trying to use react hooks in my project and I have a problem with useState when I use array as value.
As you can see in my code below, when I display zoneItems
that it should be like items
array I get an empty array all the time. Would you have an explanation why?
When I use an object instead of array it works
const ShippingCostZone = ({ zone, datas, selectedProducts, getProductById }) => {
const items = datas.items.filter(item => item.zoneId === zone.id)
console.log('========> items', items) // ---- SHOW the good values
const [zoneItems, updateItems] = useState(items)
console.log('========> zoneItems ', zoneItems) // ---- SHOW all the time []
.........
Thanks in advance
Share Improve this question asked Aug 18, 2020 at 13:51 VictorVictor 572 silver badges10 bronze badges 1- Did you ensure that all the items are not of the zone that you are using to test the functionality? Also the last console.log shows all values or just empty array []? – Kenny John Jacob Commented Aug 18, 2020 at 14:07
2 Answers
Reset to default 4Due to async nature of hooks, you assignment useState(items)
could be executed after you read the content of zoneItems
. But react provides an hook that will be fired every time ponent will be loaded, or as you prefer, every time zoneItems
changes his value: I'm talking about useEffect
hook.
So if you want to print the zoneItems
content every time is updated, just write something like this:
useEffect(() => {
console.log(zoneItems);
}, [zoneItems])
This is the way that react provides to manage async assignment of state.
I think you should initialize the state first as an array first then update it, as follows:
const ShippingCostZone = ({ zone, datas, selectedProducts, getProductById }) => {
const items = datas.items.filter(item => item.zoneId === zone.id)
console.log('========> items', items)
const [zoneItems, updateItems] = useState([])
updateitems(items)
console.log('========> zoneItems ', zoneItems)
本文标签: javascriptuseState and initial value as array does not workStack Overflow
版权声明:本文标题:javascript - useState and initial value as array does not work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745184188a2646603.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论