如何使用 useEffect 将 API 数据设置到数组中

How to set API data into an array using useEffect

我正在使用 useState Hook 将 API 数据存储到数组中。第一次渲染数据时,我得到一个空数组,在第一次渲染后我能够获取数据。

实际上,我正在尝试根据数据库中的数字数据行创建动态 select 下拉列表。

const Groups = () => {
  const [userList, setUserList] = useState();

  useEffect(() => {
    (async () => {
      const response = await fetch(
        "https://localhost:44316/api/auth/getavailableusers",
        {
          headers: {
            "Content-Type": "application/json",
          },
          credentials: "include",
        }
      );
      const content = await response.json();
      setUserList(content);
    })();
  }, []);

  return (
    <React.Fragment>
      <select id="multiselectDropdown" multiple>
        {userList.content.map((user) => (
          <option value={user.userId}>{user.name}</option>
        ))}
      </select>
    </React.Fragment>
  );
};

因为第一次渲染是空的,我得到了未定义的错误。

将空数组分配给 userList

  const [userList, setUserList] = useState([]);

并尝试使用 null 检查来避免问题

<select id="multiselectDropdown" multiple>
        {userList.length > 0 && 
         userList?.content?.map((user) => (
          <option value={user.userId}>{user.name}</option>
        ))}
      </select>

如果您还没有信息,请不要呈现。您应该确保 API 已返回一个值并像这样检查它:

{userList.content.length > 0 ? 
<select>
...
</select>
: null}

更改此代码

{userList.content.map(...)

{userList.content?.map(...)

应该可以。