使用React Context传递API返回数据为空的问题排查
问题分析与解决方案
核心问题1:重复的Context Provider覆盖全局状态
你在SearchRecipes组件里额外包裹了RecipesContext.Provider,且仅传入recipes作为value,这会覆盖外层App中RecipesContextProvider提供的上下文。当DisplayRecipes访问Context时,拿到的是内层Provider的初始空值,而非全局更新后的状态。
修改:删除SearchRecipes中的RecipesContext.Provider包裹
修改后的SearchRecipes返回部分:
return ( <div className="pb-5 pt-10 "> <div> <p className="font-[Poppins] pb-4 font-semibold text-[#464646]"> My Ingredients </p> <p className={`cursor-pointer ${ selectedIngredients.length > 0 ? "pb-4" : "" }`} > {selectedIngredients.map((ingredient, index) => ( <span key={index} pb-4 onClick={() => handleIngredientClick(ingredient)} > {ingredient}, </span> ))} </p> <div> <button className="bg-[#ffc107] px-6 rounded-md font-medium font-[Poppins] py-2 text-[1rem]" onClick={handleClick} > Find a recipe </button> </div> {/* {recipes && <DisplayRecipes recipes={recipes} />} */} </div> </div> );
核心问题2:window.open跳转导致状态丢失
window.open会打开全新页面,整个React应用重新初始化,全局Context状态随之重置为空。需使用react-router-dom的useNavigate钩子实现单页面跳转,保留应用状态。
修改1:在SearchRecipes中引入并使用useNavigate
// 顶部导入useNavigate import { useNavigate } from "react-router-dom"; const SearchRecipes = (props) => { // ...其他代码 const navigate = useNavigate(); // 初始化navigate const handleClick = async () => { try { const response = await axios.get( `${URL}?ingredients=${selectedIngredients.join(",+")}&apiKey=${APIKey}` ); setRecipes(response.data); navigate("/displayRecipes"); // 替换window.open为navigate } catch (error) { console.error(error); } }; // 可选:用useEffect监听recipes变化,验证数据是否更新 useEffect(() => { console.log("Updated recipes:", recipes); }, [recipes]); // ...其他代码 };
修改2:简化App组件,移除无用状态与方法
const App = () => { const [selectedIngredients, setSelectedIngredients] = useState([]); return ( <RecipesContextProvider> <div> <IngredientsContext.Provider value={[selectedIngredients, setSelectedIngredients]} > <NavBar /> <Routes> <Route path="/" element={<MainGrid />} /> <Route path="/displayRecipes" element={<DisplayRecipes />} /> </Routes> </IngredientsContext.Provider> </div> </RecipesContextProvider> ); };
额外说明:setState异步导致即时打印无效
handleClick中setRecipes后立刻console.log(recipes)无法拿到新值,因为React的setState是异步更新的。如需验证数据更新,使用上述useEffect监听recipes变化即可。
验证DisplayRecipes组件
修改后可尝试渲染数据测试:
import { useContext, useEffect } from "react"; import { RecipesContext } from "../contexts/recipesContext"; const DisplayRecipes = (props) => { const [recipes] = useContext(RecipesContext); console.log("DisplayRecipes recipes:", recipes); useEffect(() => { document.body.classList.add("page-styles"); return () => { document.body.classList.remove("page-styles"); }; }, []); return ( <div> <div className="mt-28 ml-4"> <h1 className="font-[Acme] text-5xl text-left text-[#ffc107] " style={{ textAlign: "left !important", marginLeft: "10px !important", }} > Recipes </h1> <div> {recipes.length > 0 ? ( recipes.map(recipe => ( <div key={recipe.id} className="mt-4"> <h3>{recipe.title}</h3> <img src={recipe.image} alt={recipe.title} /> </div> )) ) : ( <p>No recipes found</p> )} </div> </div> </div> ); }; export default DisplayRecipes;
内容的提问来源于stack exchange,提问作者AnonymousDude
相关产品推荐
相关产品推荐

