[英]React useEffect executing last function
我需要有 2 個不同的功能,在開始時只更新 2 個不同的組件一次。 因此,我正在使用useEffect
。 代碼如下
const loadCategories = () => {
getCategories().then((c) => setValues({ ...values, categories: c.data }));
}
const loadStores = () => {
getStores().then((c) => setValues({ ...values, stores: c.data }));
}
useEffect(() => {
loadStores();
loadCategories();
}, []);
這兩個函數都在設置下拉元素的值
問題是雖然這兩個函數都執行了,但只有loadCategories()
function 邏輯反映在 UI 中。 如何讓這兩個功能邏輯都反映在 UI 中?
等待兩個承諾解決,然后使用兩者中的數據更新您的 state,以您認為合適的任何方式組合。
useEffect(() => {
Promise.all([getCategories(), getStores()]).then(([categories, stores]) => {
setValues({categories, stores})
});
}, []);
您之前遇到的問題(正如您所經歷的那樣)是values
始終是在此渲染上運行useState
時的值。
如果您真的想單獨進行更新,則可以查看 useReducer: https://reactjs.org/docs/hooks-reference.html#usereducer
Promise 和useEffect
可能具有挑戰性,因為組件可能會在 promise 裝滿之前卸下。
這是一個效果很好的解決方案:
useEffect(() => {
let isRunning = true;
Promise.all([
getCategories(),
getStores()
]).then(([stores, categories]) => {
// Stop if component was unmounted:
if (!isRunning) { return }
// Do anything you like with your lazy load values:
console.log(stores, categories)
});
return () => {
isRunning = false;
}
}, []);
你在向 React 撒謊關於依賴關系。 您的兩個函數都取決於 state 變量的values
。 這也是它不起作用的原因:當鈎子運行時, values
會被關閉,然后當setValues
運行時, values
會發生變化(設置為新對象),但是在閉包內它仍然引用舊值。
您可以通過將回調傳遞給setValues
輕松解決該問題,這樣您就不會依賴外部並且值更新是原子的:
setValues(values => ({ ...values, stores: c.data }));
第一個更好的做法是將那些 function 添加到 useEffect 或將它們包裝在useCallback
鈎子中。 second both or your function are promises so each may not resolve at same time and when you trying to update state values will keep it initial value that why your first function is not reflecting in the ui instead use setState callback
to get the previous state like this :
useEffect(() => {
const loadCategories = () => {
getCategories().then((c) => setValues(prevState=>({ ...prevState, categories: c.data })));
}
const loadStores = () => {
getStores().then((c) => setValues(prevState=>({ ...prevState, stores: c.data })));
}
loadStores();
loadCategories();
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.