英文:
how to call id using useEffect and how to load data in dropdown ? based on dropdown option changing it will load & fetch the data from api
问题
请问你如何加载基于下拉选项更改的数据?一个下拉框包含类别,另一个包含产品列表。如果我选择一个类别,它将加载该类别下的产品。
useEffect(() => {
const getcategory = async () => {
try{
const res = await fetch("http://localhost:5000/PortfolioGroup");
if (!res.ok) throw Error('未收到预期的数据')//return await res.json();
const getdata = await res.json();
setCategory(getdata);
console.log(getdata);
setFetchError(null);
} catch (err) {
setFetchError(err.message);
}
}
const getproductlist = async (portfolioId) => {
try{
const res = await fetch("http://localhost:5000/manasa");
if (!res.ok) throw Error('未收到预期的数据');
//return await res.json();
const getdata = await res.json();
setCategory(getdata);
console.log(getdata);
setFetchError(null);
} catch (err) {
setFetchError(err.message);
}
}
setTimeout(() => getcategory(), 2000);
setTimeout(() => getproductlist(), 2000);
getproductlist();
},[]);
这是您提供的代码的中文翻译部分。
英文:
could you please help me how to load the data based on dropdown options changing. one dropdown contains category and another one contains products list. if i select one category it will load that products under based on that category.
useEffect(() => {
const getcategory = async () => {
try{
const res = await fetch("``http://localhost:5000/PortfolioGroup``");
if (!res.ok) throw Error('Did not receive expected data')//return await res.json();
const getdata = await res.json();
setCategory(getdata);
console.log(getdata);
setFetchError(null);
} catch (err) {
setFetchError(err.message);
}
}
const getproductlist = async (portfolioId) => {
try{
const res = await fetch("http://localhost:5000/manasa");
if (!res.ok) throw Error('Did not receive expected data');
//return await res.json();
const getdata = await res.json();
setCategory(getdata);
console.log(getdata);
setFetchError(null);
} catch (err) {
setFetchError(err.message);
}
}
setTimeout(() => getcategory(), 2000);
setTimeout(() => getproductlist(), 2000);
getproductlist();
},[]);
答案1
得分: 1
调用 getcategory
方法在 componentDidMount
或
useEffect(() => {getcategory()}, [])
现在,每当您的类别值更改,您必须调用 getproductlist
,因此请在依赖数组中放置一个 useEffect
和类别值,如下所示。
useEffect(() => {
if(category) {
getproductlist(category.portfolioId)
} else {
setProductList([])
}
}, [category])
英文:
call the getcategory method on componentDidMount or
useEffect(() => {getcategory()}, [])
Now you have to call getproductlist whenever your category value changes so put a useEffect and category value in dependency array as shown below.
useEffect(() => {
if(category) {
getproductlist(category.portfolioId)
} else {
setProductList([])
}
}, [category])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论