本文探讨了在react应用中,通过点击不同分类按钮动态调用api的正确方法。针对`
在深入探讨解决方案之前,我们先明确动态API调用的核心React逻辑。这部分代码负责管理当前选中的分类状态,并在分类变化时触发API请求。
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const API_BASE_URL = "https://www.themealdb.com/api/json/v1/1/filter.php?c="; // 示例API基础URL
function CategoryFilter() {
const [category, setCategory] = useState(""); // 存储当前选中的分类
const [meals, setMeals] = useState([]); // 存储API返回的菜品数据
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (!category) return; // 如果没有分类,则不发起请求
setLoading(true);
setError(null);
axios.get(`${API_BASE_URL}${category}`)
.then(functio
n (response) {
setMeals(response.data.meals || []); // 更新菜品数据,如果无数据则为空数组
console.log(`Fetched ${category} meals:`, response.data.meals);
})
.catch(function (error) {
console.error("API call error:", error);
setError("Failed to fetch data. Please try again.");
setMeals([]); // 清空数据
})
.finally(() => {
setLoading(false);
});
}, [category]); // 依赖项:当category变化时重新运行effect
// onClickHandler的实现将在下面两种解决方案中给出
return (
分类食谱
{/* 分类按钮/列表将在这里渲染 */}
{loading && 加载中...
}
{error && {error}
}
{!loading && !error && meals.length === 0 && category && 未找到 {category} 分类的食谱。
}
{!loading && !error && meals.length > 0 && (
{meals.map((meal: any) => (
- {meal.strMeal}
))}
)}
);
}
export default CategoryFilter; 接下来,我们将介绍两种正确的解决方案来获取点击事件中的分类值。
最直接且符合语义化的解决方案是使用
HTML/JSX 代码:
// 在 CategoryFilter 组件的 return 语句中分类食谱
{/* ... 其他内容 (loading, error, meals 渲染) ... */}
事件处理函数:
onClickHandler函数可以保持不变,因为e.target.value现在会正确地获取到按钮的value属性。
const onClickHandler = (e: React.MouseEvent) => { setCategory(e.currentTarget.value); // 使用 currentTarget 确保获取到点击的按钮本身的值 };
优点:
如果出于布局或样式考虑,仍然希望使用
HTML/JSX 代码:
// 在 CategoryFilter 组件的 return 语句中分类食谱
{/* ... 其他内容 (loading, error, meals 渲染) ... */}
事件处理函数:
在这种情况下,你需要修改onClickHandler来从data-value属性中获取数据。
const onClickHandler = (e: React.MouseEvent) => { // 使用 getAttribute 获取 data-value 属性的值 setCategory(e.currentTarget.getAttribute("data-value") || ""); };
优点:
在React中实现点击不同分类调用API的功能时,关键在于正确地从点击事件中获取分类值。避免将自定义数据存储在