reactjs - 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 函数中更改了“测试”,但这会导致页面根本不呈现的无限循环。
解决方案
将获取/设置数据的函数移到效果之外,然后在之后调用该函数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);
}
};
推荐阅读
- c# - 通过 Span 修改变量时,优化构建和 JIT 编译是否会产生问题
? - python - 无法在树莓派 3 b+ 上卸载 python/pip
- python - Python 中的递归、记忆和可变默认参数
- java - 替换具有后拉力的变量
- jenkins - 如何在 Jenkinsfile groovy map 中定义和获取/放置值
- python - 从不同子图中的每一列绘制 seaborn 直方图(facetgrid)
- mysql - 如何使用mysql选择字段值作为列名和行
- sql - 为每个用户选择最新和第二个最新日期行
- php - 从同一个表中复制(更新)某些内容
- mysql - 为多行创建触发器