无法在useState挂钩中设置数组 [英] Unable to set array in useState hook

查看:717
本文介绍了无法在useState挂钩中设置数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,我正在尝试在setUsers中设置数组,数据正确地来自后端,但未成功设置钩子请帮助我

This is my code i am trying to set array in setUsers the data comes properly from backend but it does not get set in hook please help me

const LoadAllUser = () => {
  const [users, setUsers] = useState([]);
  const loadUsers = () => {
    loadalluser()
      .then((data) => {
        if (data.error) {
          console.log(data.error);
          // setusers(data.error);
        } else {
          setUsers(data);
        }
      })
      .catch((eror) => console.log("error is here"));
  };
  useEffect(() => {
    loadUsers();
  }, []);

我的回报是这样的

return (
    <div>
      {users.length > 0 ? (
        users.map((index, user) => {
          return (
            <div key="index">
              <label>Name : {user.name}</label>
              <label>Email : {user.email}</label>
              <label>NUmber : {user.number}</label>
            </div>
          );
        })
      ) : (
        <h1> No users found </h1>
      )}
      )
    </div>
  );

这就是我获取所有用户的方式

And this is how i fetch all of my users

export const loadalluser = (users) => {
  return fetch(`${API}/loadalluser`, {
    method: "GET",
    body: JSON.stringify(users),
  })
    .then((response) => {
      return response.json();
    })
    .catch((error) => {
      return error;
    });
};


推荐答案

获取仅拒绝已取消的请求或网络错误,否则将返回已解决的Promise。

fetch only rejects on cancelled requests or network errors, otherwise it returns a resolved Promise.

检查是否成功获取


A <$ c当遇到网络错误
或服务器上错误配置了CORS时,$ c> fetch()承诺将拒绝并显示 TypeError ,方面,尽管此
通常意味着权限问题或类似问题,例如404并不构成
a网络错误。准确检查成功的
fetch()包括检查承诺是否已解决,然后
检查 Response。 ok 属性的值为true。

A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true.

您应检查 response.ok 以确保请求成功或失败。您也可能会删除catch块,因为使用组件代码中的任何catch块都会捕获它们。

You should check response.ok to ensure the request was successful or not. You can also likely also remove the catch block as any catch blocks in the consuming component code will catch them.

export const loadalluser = (users) => {
  return fetch(`${API}/loadalluser`, {
    method: "GET",
    body: JSON.stringify(users),
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    });
};

此更改应通过 not 静默吞下失败的获取请求并使用错误的值更新状态来提供帮助。

This change should help by not silently swallowing failed fetch requests and update state with bad values.

此外,您是否需要将个用户传递给 loadalluser 的GET请求?

Also, do you need to pass users to loadalluser for the body of the GET request?

这篇关于无法在useState挂钩中设置数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆