我正在尝试更新状态。我一直在读,为了不完全替换状态,需要使用传播运算符。在将状态附加到先前状态时,它的工作量很大,但我在将状态附加到正确的位置时仍在努力。下面的代码更新了“类别”的状态,但它与“ all_categories”和“ current_category”处于同一级别。我希望将获取的对象放入“ all_categories”中。谢谢。
const [ categories, setCategory ] = useState({
all_categories: [],
current_category: 'Cocktail'
});
const [recipes, setRecipe] = useState([]);
useEffect(() => {
Promise.all(
[
fetch(`https://the-cocktail-db.p.rapidapi.com/filter.php?c=${categories['current_category']}`, {
"method": "GET",
"headers": {
"x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
"x-rapidapi-key": "xxx"
}
}),
fetch("https://the-cocktail-db.p.rapidapi.com/list.php?c=list", {
"method": "GET",
"headers": {
"x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
"x-rapidapi-key": "xxx"
}
})
]
)
.then(([response1, response2]) => {
return Promise.all([response1.json(), response2.json()])
})
.then(([drinks_data, categories_data]) => {
setRecipe(drinks_data['drinks'])
setCategory(prev_state => {
return {...prev_state, ...categories_data['drinks']};
});
})
.catch(err => { console.log(err); });
},[]);
You have to update the
all_categories
key within category state and merge the individual category values using spread syntax like below