简体   繁体   中英

Push array of an object to array

    const [ post, setPost] = useState([])

    function addMemo() {
        let memo = [
                { id:1, name:'shyam', post:'developer' },
                { id:2, name:'ram', post:'porter' },
                { id:3, name:'prakash', post:'cobler' },
                { id:4, name:'sanj', post:'designer' },
                { id:5, name:'anil', post:'pilot' },
                { id:6, name:'gopal', post:'laptain' }
            ]
        
        setPost( [...post, memo] )
     }

    return (
         <button type="button" onClick={() => addMemo()}>Click Me</button>
   )

here is my code but I could not push array of object to the existing array Push array of an object to existing array,

Use ... spread operator for the memo .

    setPost( [...post, ...memo] )

Whenever you are updating state based on previous state it is better to pass a function to the setState function.

setPost((prevPost) => [...prevPost, memo] )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM