首页 > 解决方案 > 如何在 ReactJS 中处理增加和减少帖子

问题描述

我目前有点卡在这一点上,我确定我在做一些愚蠢的事情(我也在尝试不重复自己,因为我正在获取帖子 3 次,不要杀了我我是新手这),我正在尝试通过增加/减少按钮方案来更改帖子的数量。到目前为止,我正在导致不必要的重新渲染以及计数器关闭(我必须单击它两次才能转到正确的帖子),我该如何解决这个问题?代码如下:

import React, {useEffect, useState} from 'react'
import axios from 'axios'

export const Login = () => {
    const [data, setData] = useState({});
    const [counter, setCounter] = useState(1);

    useEffect(() => {
        fetchPosts()
    } ,[]);

    const handleIncrease = () => {
        setCounter(counter + 1);
        fetchPosts();
    };

    const handleDecrease = () => {
        setCounter(counter - 1);
        fetchPosts();
    };

    const fetchPosts = () => {
        const options = {
            url: `https://jsonplaceholder.typicode.com/posts/${counter}`,
            method: "GET",
            headers: {
                'Content-type': 'application/json; charset=UTF-8',
            },
        };

        return (
            axios(options)
                .then((response) => {
                    return setData(response.data)
            })
        )
    };

    return (
        <div>
            <button onClick={handleIncrease}>add one</button>
            <button onClick={handleDecrease}>{console.log(data)}Subtract one</button>
        </div>

    )
};

标签: javascriptreactjs

解决方案


尝试使用此代码。在此代码中,每次计数器值更改时都会调用 useEffect,这意味着计数器值在 handleIncrease 和 handleDecrease 函数上发生更改,并且还会从 handleIncrease 和 handleDecrease 中删除 fetch 函数。fetch 函数也是在 useEffect 之前声明的。

import React, {useEffect, useState} from 'react'
    import axios from 'axios'

    export const Login = () => {
        const [data, setData] = useState({});
        const [counter, setCounter] = useState(1);
       const fetchPosts = () => {
            const options = {
                url: `https://jsonplaceholder.typicode.com/posts/${counter}`,
                method: "GET",
                headers: {
                    'Content-type': 'application/json; charset=UTF-8',
                },
            };

            return (
                axios(options)
                    .then((response) => {
                        return setData(response.data)
                })
            )
        };

        useEffect(() => {
            fetchPosts()
        } ,[counter]);

        const handleIncrease = () => {
            setCounter(counter + 1);
        };

        const handleDecrease = () => {
            setCounter(counter - 1);
        };


        return (
            <div>
                <button onClick={handleIncrease}>add one</button>
                <button onClick={handleDecrease}>{console.log(data)}Subtract one</button>
            </div>

        )
    };

推荐阅读