简体   繁体   中英

Insert an array into state using useState hook in React

I'm a newbie to React. Trying to insert an array of data into a variable using useState() hook in a functional component. When I do this, I was getting this error

Expected 1 arguments, but got 0 or more.ts(2556)

Code

const data = [{
  title: 'React',
  'description': 'State in React'
}, {
  title: 'Angular',
  'description': 'Introducing Typescript'
}]

const [posts, setPosts] = useState([]);

setPosts(data)

Could anyone please help?

I made a simple functional component "Home" based on your code and it works correctly. The code is below:

import React, { useState } from 'react'

const Home = () => {
  const [posts, setPosts] = useState([])
  const data = [
    {
      title: 'React',
      description: 'State in React'
    },
    {
      title: 'Angular',
      description: 'Introducing Typescript'
    }
  ]

  return (
    <div>
      <button type="button" onClick={() => setPosts(data)}>
        Data
      </button>
      <div>
        Data from State:
        {posts.map((obj) => {
          return <div key={obj.title}>{obj.title}</div>
        })}
      </div>
    </div>
  )
}

export default Home

If this answere was helpful please mark it.

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