我正在使用react hooks应用程序,在其中我可以获取鸡尾酒食谱并显示它们。从API最初获取鸡尾酒后,我将它们设置为本地存储,并使用本地存储在我的页面中显示这些鸡尾酒。为此,我需要以下代码
const getSearchTerm = async (searchTerm) => {
const result = await axios(`https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${searchTerm}`);
let SetLocalStorage = () => {
localStorage.setItem('results', JSON.stringify(result));
};
function run(callback) {
localStorage.clear();
callback();
}
run(SetLocalStorage);
};
当我尝试使用以下代码从本地存储中解析并映射此内容时,就会发生问题
const displayRecipes = () => {
if (parsedResultsFromLocalStorage) {
return parsedResultsFromLocalStorage.data.drinks.map((recipe) => (
<RecipeCard
strDrink={recipe.strDrink}
strDrinkThumb={recipe.strDrinkThumb}
strGlass={recipe.strGlass}
drink={drink}
key={uuidv4()}
/>
));
} else {
return (
<p className="font-style-1 ResultsPage-error-message">
Uh oh, we don't seem to have anything for {drink}. Did you spell that right?
</p>
);
}
};
页面加载后,食谱卡组件中显示的是上次搜索而不是当前搜索所调用的数据。发生这种情况的原因是,在使用我的新搜索字词中的新数据填充本地存储之前,该新页面加载速度过快。我知道这是因为,一旦我重新加载页面,旧数据就消失了,并且配方卡具有了我想要的初始渲染中的数据。
所以我的问题是,在运行displayRecipes()之前,是否还要等到从我的新搜索词中提取内容并将其填充到本地存储中?