我目前在这方面有些卡住,我确定自己在做些愚蠢的事情(我也在尝试不重复自己,因为我要抓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函数。也取
函数在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 - 如何解决ReactJS中的增加和减少发布,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59260935/