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>
)
};
解决方案
尝试使用此代码。在此代码中,每次计数器值更改时都会调用 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>
)
};
推荐阅读
- javascript - 在 chrome 上使用 requestAnimationFrame 每 100 毫秒调用一个函数
- python - 为什么我会收到错误消息“start_time is not defined”?
- python-3.x - 如何使用 numpy 从多个数组中获取相同索引的值?
- angular - 将具有 svg 文件的 Angular 组件选择器作为 templateUrl 从主路由组件动态传递到其他共享的 Angular 组件,而无需 *ngIf
- python - 如果在另一列中包含字符串,则在其中一列中返回“是”
- javascript - 是否有任何合适的 API 可以编写 chrome 扩展来下载 cookie 身份验证后的图像?
- r - 从闪亮的 Web 应用程序将 csv 或 xslx 文件写入光盘
- javascript - Redux 动作道具意外行为
- laravel - 需要将 Laravel 项目中的哪些文件夹和文件部署到服务器?
- javascript - 将 jQuery 函数的结果应用回所选元素?