开发者问题收集

如何在 React 中使用 useEffect 获取数据

2021-05-07
55

我试图使搜索栏在 searchQuery === "" 时清除输入中的所有单词,用户列表将清除,数据将消失。

这是我的代码:

const Invitees = (props) => {
  const [searchQuery, setSearchQuery] = useState("");
  const [invitees, setInvitees] = useState([]);

  const handleChange = (event) => {
    event.preventDefault();
    setSearchQuery(event.target.value);
  };

  const handleSubmit = async () => {
    const res = await axios.get(`/api/v1/search/users/invite/${searchQuery}`);
    setInvitees(res.data[0]);
  };

  useEffect(() => {
    if (searchQuery === "") {
      setInvitees([]);
    }
  }, []);

  return (
    <div className="invitees-container">
      <div className="invitees-wrapper">
        <div className="invitees-sortes">
          Sort by: <u>Recommended</u>{" "}
          <svg
            width="12"
            height="6"
            viewBox="0 0 12 6"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M6 6L0.803848 0L11.1962 0L6 6Z" fill="#A9A9A9" />
          </svg>
        </div>
        <div className="invitees-search">
          <Button
            className="input invitees--search-icon"
            style={{ color: "white", backgroundColor: "#00B790" }}
            type="submit"
            onClick={handleSubmit}
          >
            <SearchIcon />
          </Button>
          <input
            className="invitees--search_input"
            type="search"
            name="name"
            onChange={handleChange}
            placeholder="Name, Skill, Location"
            aria-label="Search bar"
            pattern="^[a-zA-Z0-9 ]+"
            required
          />
        </div>
      </div>
      <Grid
        container
        direction="row"
        justify="flex-start"
        alignItems="stretch"
        spacing={6}
      >
        {invitees.map((user, index) => (
          <Grid item className="invitees-card" key={index}>
            {user.Memberships.length < 1 && <InviteCard user={user} />}
          </Grid>
        ))}
      </Grid>
    </div>
  );
};

我如何实现该功能?

3个回答

需要在 useEffect 中添加依赖项:

  useEffect(() => {
    if (searchQuery === "") {
      setInvitees([]);
    }
  }, [searchQuery ]);
Viet
2021-05-07

在句柄更改中添加条件

 const handleChange = (event) => {
    event.preventDefault();
    if (event.target.value === '') {
       setInvitees([])
    }
    setSearchQuery(event.target.value);
  };
Someone Special
2021-05-07
   axios
     .get('/api/v1/search/users/invite/${searchQuery}')
     .then((res) => res.data)
     .then((data) => setInvitees(data[0]));
 }, []);

试试看?

我认为你的 axios 确实应该在 useEffect 中。

并且你在其中保留你想要的条件。

Flavien Besseau
2021-05-07