首页 > 解决方案 > API调用后再次触发useEffect

问题描述

我有以下 useEffect 钩子,它在页面的初始加载时运行

useEffect(() => {
  const getLeads = () => axios.get("/api/leads");

  const setLeadState = async () => {
    try {
      const res = await getLeads();
      res.data.map(lead => setLeads(prevState => [...prevState, lead]));
    } catch (err) {
      console.error(err);
    }
  };
  setLeadState();
}, []);

然后我有以下功能可以将新数据添加到 api。此函数在表单提交时调用。

const addLead = async (firstName, lastName, email) => {
  try {
    const body = {
      firstName,
      lastName,
      email
    };
    const res = await axios.post("api/leads", body);
  } catch (err) {
    console.error(err);
  }
};

执行 addLead 函数后,如何再次调用我的 useEffect 挂钩?我尝试过这样的事情

const [test, setTest] = useState("");

useEffect(() => {
  const getLeads = () => axios.get("/api/leads");

  const setLeadState = async () => {
    try {
      const res = await getLeads();
      res.data.map(lead => setLeads(prevState => [...prevState, lead]));
    } catch (err) {
      console.error(err);
    }
  };
  setLeadState();
}, [test]);

然后在 addLead 函数中更改了“测试”,但这会导致页面根本不呈现的无限循环。

标签: reactjsreact-hooks

解决方案


将获取/设置数据的函数移到效果之外,然后在之后调用该函数addLead

const getLeads = () => axios.get("/api/leads");

const setLeadState = async () => {
  try {
    const res = await getLeads();
    res.data.map(lead => setLeads(prevState => [...prevState, lead]));
  } catch (err) {
    console.error(err);
  }
};

// Initial load
useEffect(() => {
  setLeadState();
}, []);

const addLead = async (firstName, lastName, email) => {
  try {
    const body = {
      firstName,
      lastName,
      email
    };
    const res = await axios.post("api/leads", body);
    // Load again
    setLeadState();
  } catch (err) {
    console.error(err);
  }
};


推荐阅读