为什么在 prop 状态改变后功能组件没有重新渲染?

时间:2021-07-19 21:21:44

标签: reactjs react-hooks

我在 useEffect 内部有这个函数,它调用 API 并在完成时使用值设置“货架”状态,我预计依赖货架状态的组件会在更新此状态时再次呈现,但事实并非如此,有什么问题?

主要组件:

import Head from 'next/head'

import fetchGoogleBooks from '../library/fetchGoogleBooks'

import Header from '../components/Header'
import Library from '../components/Library'
import Results from '../components/Results'

import { Container } from '../styles/pages/Home'

import shelvesList from '../../shelvesList.json'

import Shelf from '../types/Shelf'
import Book from '../types/Book'

const Home: React.FC = () => {
  const [shelves, setShelves] = useState<Shelf[]>(null)
  const [results, setResults] = useState<Book[]>(null)
  const [isOnResults, setIsOnResults] = useState<boolean>(false)

  const searchFor = async (search: string) => {
    if (search.length !== 0) {
      const fetchedBooks = await fetchGoogleBooks(
        `volumes?q=${search}&maxResults=10`
      ).then(response => response.data.items)

      setResults(fetchedBooks)
      setIsOnResults(true)
    }
  }

  const fetchShelves = async () => {
    const fetchedShelves = []

    shelvesList.forEach(async shelf => {
      fetchedShelves.push({
        title: shelf.title,
        books: await fetchGoogleBooks(
          `volumes?q=${shelf.title}&maxResults=10`
        ).then(response => response.data.items),
        style: shelf.style
      })
    })

    setShelves(fetchedShelves)
  }

  useEffect(() => {
    fetchShelves()
  }, [])

  return (
    <Container>
      <Head>
        <title>Home</title>
      </Head>

      <Header
        searchFor={searchFor}
        isOnResults={isOnResults}
        goBackHome={() => setIsOnResults(false)}
      />
      {shelves !== null && <Library shelves={shelves} />}
      {/* {isOnResults && <Results />} */}
    </Container>
  )
}

export default Home

应该更新的组件:

import React from 'react'

import { Container, Shelf, Book } from './styles'

import ShelfType from '../../types/Shelf'

interface LibraryProps {
  shelves: ShelfType[]
}

const Library: React.FC<LibraryProps> = ({ shelves }) => {
  return (
    <Container>
      {shelves.map(shelf => (
        <Shelf key={shelf.title}>
          <h2>Aventura</h2>
          <div>
            <Book>
              <img src="https://books.google.com.br/books/content?id=UpCkPvlPffYC&printsec=frontcover&img=1&zoom=1&edge=curl&imgtk=AFLRE709s_ZmSdYHTD0yBj3O2qwGQohKPHSlWxic_PfZUiZF36D6garBez6d00aPnXEKrFQFz3CnOmzIM-EQ33cTxqqBR0pZrcNxPZiGLB_a9Ut5vre4h5IgpAcibb7uHJ9Krkhf6Ibw"></img>
              <h3>A Panela do Menino Maluquinho</h3>
            </Book>
          </div>
        </Shelf>
      ))}
    </Container>
  )
}

export default Library

0 个答案:

没有答案