javascript - 在 React 中使用 useState 在 Promise 中设置状态时,应用程序会不断重新渲染
问题描述
我想调用一个休息端点,检索一组项目并将它们显示在页面中。
const [users, setUsers] = useState([]);
axios
.get("https://reqres.in/api/users")
.then(response => {
console.log(response);
setUsers(response.data.data);
})
.catch(function(error) {
// handle error
console.log(error);
});
return (
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.length &&
users.map(user => (
<tr key={user.id}>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
<td>{user.email}</td>
</tr>
))}
{users.length === 0 && "Loading..."}
</tbody>
</table>
</div>
);
但是,该应用程序会不断重新渲染。我试图将 ajax 调用放在useEffect
回调中,但它没有......效果
这是一个带有代码的沙箱的链接:Codesandbox
解决方案
您需要将您的 api 调用移动到useEffect
钩子中:
useEffect(() => {
axios
.get("https://reqres.in/api/users")
.then(response => {
console.log(response);
setUsers(response.data.data);
})
.catch(function(error) {
// handle error
console.log(error);
});
}, [])
推荐阅读
- javascript - 将 jQuery 转换为 JavaScript 以进行 Google Analytics pdf 下载跟踪
- asp.net-core - 使用 EntityFrameworkCore 向 ASP.NET Core 项目添加标识时出现问题
- python - 如何在 Django 中使用 Hardcopy 在所选目录中创建 pdf 输出文件?
- apache - 如何从请求体内部发送巨大的 JSON?测量仪
- python - Selenium Webdriver .get() 没有打开窗口 - 没有错误
- c# - How to return the selected value from a Razor Page dropdown to a c# variable?
- git - 为什么 GIT 命令行突然停止工作并出现“SSL 证书问题:无法获取本地颁发者证书”
- passport.js - 在 SP 回调中确定是 IDP 发起还是 SP 发起?
- python - 如何在熊猫或python中分割具有特定范围的日期
- python - Exclude option in select that's already choosen by user