如何解决ReactJS中的增加和减少发布

时间:2019-12-10 05:43:45

标签: javascript 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>

    )
};

2 个答案:

答案 0 :(得分:3)

  

尝试使用此代码。在此代码中,每次都调用useEffect   计数器值发生变化,这意味着计数器值发生变化   handleIncrease和handleDecrease函数,也删除获取   从handleIncrease和handleDecrease函数。也取   函数在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>

        )
    };

答案 1 :(得分:0)

您的问题可能与同步有关。由于Axios是异步的,您可能要使用async ()await。首次单击时,将调用GET请求,但是您的代码将在GET请求之前返回。再次单击时,get请求已返回,并且值已更新。异步“阻止”直到返回值,然后继续执行。

例如,您可能想要类似的东西。

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

    let res = await axios.get(options).then((response) => {
                    return setData(response.data)
            })
    return res;
};

以供参考:https://medium.com/better-programming/how-to-use-async-await-with-axios-in-react-e07daac2905f