首页 > 解决方案 > 在 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

标签: javascriptajaxreactjs

解决方案


您需要将您的 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);
    });
}, [])

更新的沙盒


推荐阅读