简体   繁体   English

使用 React 中的 useState 钩子将数组插入 state

[英]Insert an array into state using useState hook in React

I'm a newbie to React.我是 React 的新手。 Trying to insert an array of data into a variable using useState() hook in a functional component.尝试使用功能组件中的useState()挂钩将数据数组插入到变量中。 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.我根据您的代码制作了一个简单的功能组件“Home”,它可以正常工作。 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.如果这个答案有帮助,请标记它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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