I am trying to use React useState to store an array of objects but I'm having a strange problem. The state will not take on the value I give it. I have tried all of the following:
const [items,setItems] = useState(props.items)
const [items,setItems] = useState([...props.items])
const clone = [...props.items]
const [items,setItems] = useState(clone)
but the value of items after each solution is an empty array. Even when props.items
is not an empty array.
It works when I do for example
const demo = [{hello:'world'}]
const [items,setItems]=useState(demo)
Does anyone know the problem?
EDIT:
Concrete example:
This is the relevant part of the calling (parent) react functional element
const overviews = props.overviews.map((obj, index) => ({ ...obj, onClick: myOnClick}));
return <DragSort items={overviews}/>
then
const Dragsort = (props) => {
const [ items, setItems ] = useState(props.items);
console.log('dragsort 1:', props.items);
console.log('dragsort 2:', items);
console.log('dragsort 3:', props.items instanceof Array);
console.log('dragsort 4:', items instanceof Array);
...
gives
Try to ensure that you are checking the result for the first time that the component is rendering. What may be happening is that you are looking at the result for the 2nd, or nth render, and at this point the state has already been set to a incorrect (in this case an empty array) value.
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.