反应 useEffect 钩子并返回数据

时间:2021-04-30 20:03:44

标签: reactjs

我仍在学习 React 和它的钩子,我一直遇到一个我无法弄清楚的问题。

简而言之,我使用 useEffect 和 useState 从 postgres 数据库中提取数据,并使用 express 作为中间件。路线工作并且一切都处于活动状态并正在运行,但是,它不断返回空白数据。我正在尝试将其设置为吐出列表中的每个项目。我首先想到可能与我如何传递道具有关,但我所看到的一切都向我表明它被正确传递。我没有想法,所以我试一试。

这是父代码:

import React, {useEffect, useState} from 'react'
import Catalogitems from './Catalogitems.jsx'


function Catalog() {
  const [books, setbooks] = useState([])
  const url = "http://localhost:3001/api/books/"

  const getData = () =>
    fetch(url)
    .then((res) => res.json())

    useEffect(() => {
      getData().then((data) => setbooks(data))
    },[])
 


  return (
    <div>
    
      {books.map(item => <Catalogitems props={item} />)}

    </div>
  )
}

export default Catalog

这是孩子:

import React from 'react'
function Catalogitems({title, author, ISBN, genre_id,front_cover_image}) {
  return (
    <div className="catalogItem">
      <img  className="bookpicture" src={front_cover_image} alt="Broken picture link" />
      <h1>{title}</h1>
      <p> Author:{author}</p>
      <p>ISBN: {ISBN}</p>
      <p>Genre: {genre_id}</p>

    </div>
  )
}

export default Catalogitems

这是来自服务器的示例响应:

 {
    "books_id": 1,
    "title": "Monster Hunter",
    "author": "R.L. Stine",
    "ISBN": "123456",
    "front_cover_image": 1,
    "genre_id": 1
  }

2 个答案:

答案 0 :(得分:0)

尝试使用 spread 来传递整个数组/对象

答案 1 :(得分:0)

您在此处传递了一个 名为“道具”的道具:

{books.map(item => <Catalogitems props={item} />)}

然而,你的子组件并不期待“道具”道具;如果这样做,它看起来像这样:

function Catalogitems({props}) {
  const {title, author, ISBN, genre_id,front_cover_image} = props;
  // ...

可以在参数中解构它,就像这样:

function Catalogitems({props: {title, author, ISBN, genre_id,front_cover_image}}) {

但是(正如@Pauline 指出的)一个更简单的解决方法是将您的 item “分散”到多个道具中,如下所示:

{books.map(item => <Catalogitems {...item} />)}

这样做可以让您保留您的原始目录项签名:

function Catalogitems({title, author, ISBN, genre_id,front_cover_image}) {

附言作为旁注,通常使用大写的新单词命名变量,例如。 CatalogItemssetBooks