【发布时间】:2021-05-18 18:06:16
【问题描述】:
我在 useEffect() 中获取所有用户的事务,但是当我创建一个新事务时,useEffect 不会重新加载,那么我需要刷新页面才能看到更改。我已经进行了很多搜索,并且尝试了诸如 useCallback() 和 useRef() 和 useEffect() 之类的方法,但仍然无法正常工作,可能是因为我不太了解如何正确使用它们。当我传递我想要观看的数据时,在我的情况下 [transactions] 我得到一个无限循环,因为 setState 会混淆我的状态,然后组件将重新加载,因此 useEffect 将调用我的函数并且 setState 将被触发,这将发生重新来过。
const [transactions, setTransactions] = useState([]);
useEffect(() => {
getUserTransactions();
}, []);
const getUserTransactions = async () => {
if (currentUser) {
const token = await firebase.auth().currentUser.getIdToken();
axios
.get("http://localhost:8080/transactions", {
headers: {
"Content-Type": "application/json",
Authorization: token,
},
})
.then((res) => {
setTransactions(res.data);
})
.catch((err) => console.log(err));
}
};
我想知道异步操作是否会导致这个问题,因为在另一个项目中,我没有遇到任何问题。
const createTransaction = async (e) => {
e.preventDefault();
if (currentUser) {
const token = await firebase.auth().currentUser.getIdToken();
const data = {
title: textRef.current.value,
price: priceRef.current.value,
category: categoryRef.current.value,
};
axios
.post("http://localhost:8080/transactions", data, {
headers: {
"Content-Type": "application/json",
Authorization: token,
},
})
.then((res) => {
setTransactions(prevTransactions => [...prevTransactions, res.data.rows])
})
.catch((err) => console.log(err));
setIsOpen(false);
}
};
【问题讨论】: