[英]How to set the state in useEffect in React?
我目前正在做一個項目,我需要從后端獲取特定數據並設置對象。 但是,它沒有正確設置對象,它只是設置最后一個元素。
我正在使用 ContextAPI 進行狀態管理。
我的 API 請求如下所示,用於從整個產品返回特定產品( axios
我設置了一個掛鈎,它獲取uid
,函數本身獲取id
,這是一個產品id
):
const getProductbyId = async (id) => {
try {
const response = await axios.get("designer/products", {
uid: currentAuthData.id,
});
const products = response.items;
const product = products.filter((item) => item.id === parseInt(id));
return product[0];
} catch (error) {
return null;
}
}
在我的 React 代碼中,我使用useEffect
獲取特定數據並將其添加到對象中。
這里的data
是我正在使用的上下文,它包含幾個狀態。 但是,我需要在這里使用data.setValues
。
const data = useData();
const params = useParams();
useEffect(() => {
data.setValues({
...data.values,
step1: 1,
});
const getProductbyId = async () => {
const response = await data.requests.getProductbyId(params.id);
if (response) {
response.property_groups.forEach((item, i) => {
data.setValues({
...data.values,
[`step${i + 2}`]: item.group_property.id,
});
});
}
};
getProductbyId();
data.setStep(2);
}, []);
問題出現在data.setValues
中,它沒有將值(即ids
)添加到對象。
我嘗試使用useTimeout
但它沒有解決問題。 總而言之,我想將值添加到data.values
對象並在另一個 React 代碼中使用它。
像這樣改變你的方法,
const getProductbyId = async () => {
const response = await data.requests.getProductbyId(params.id);
if (response) {
let newValues=response.property_groups.reduce((prev,item,i)=>{
prev[`step${i + 2}`]= item.group_property.id;
return prev;
},{});
data.setValues({
...data.values,
...newValues
});
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.