useEffect()可以在分页时重新呈现

时间:2020-04-28 02:17:06

标签: javascript reactjs frontend use-effect use-state

import React, {useEffect, useState} from 'react'
import api from '../../services/api'
import './styles.css'

export default function Main(){
    const [products, setProducts] = useState([])
    const [page, setPage] = useState(1)
    const [productsInfo, setProductsInfo] = useState({})

    useEffect(() => {
        async function fetchData() {
            const response = await api.get(`/?page=${page}`)

            const {docs, ...info} = response.data

            setProductsInfo(info)
            setProducts(docs)
        }
        fetchData()
    }, [page])

    function prevPage() {
        if(page > 1) setPage(page - 1)
    }

    function nextPage() {
        if(page < productsInfo.pages) setPage(page + 1)
    }

    return(
        <div className='products-list'>
            {console.log(products)}
            {products.map(product => (
                <article key={product._id}>
                    <strong>{product.title}</strong>
                    <p>{product.description}</p>

                    <a href="#">Access</a>
                </article>
            ))}
            <div className="actions">
                <button onClick={prevPage()}>Previous</button>
                <button onClick={nextPage()}>Next</button>
            </div>
        </div>
    )
}

这是我的应用程序页面,用于获取产品API的数据(使用axios)。响应是具有以下结构的JSON:

{
  "docs": [
    {
    ####Product 1 info here###
    },
    {
    ###Product 2 info here###
    }
  ],
  "total": 19,
  "limit": 5,
  "page": "1",
  "pages": 4
}

我只想在页面更改时重新获取并重新呈现产品,因此我将[page]作为useEffect()的参数传递。函数prevPage()和nextPage()处理页面更改。

由于某种原因,它返回错误:重新渲染过多。 React限制了渲染次数以防止无限循环。

1 个答案:

答案 0 :(得分:2)

作为箭头函数调用

<button onClick={() => prevPage()}>Previous</button>
<button onClick={() => nextPage()}>Next</button>