本文旨在解决在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
function CategoryFilter() {
const [category, setCategory] = useState("Seafood"); // 初始分类
const [meals, setMeals] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!category) return; // 如果没有分类,则不发起请求
setLoading(true);
setError(null);
axios
.get(`${API_BASE_URL}${category}`)
.then(function (response) {
setMeals(response.data.meals || []); // 确保即使没有数据也设置为空数组
})
.catch(function (err) {
console.error("API Error:", err);
setError("加载数据失败,请稍后再试。");
setMeals([]);
})
.finally(() => {
setLoading(false);
});
}, [category]); // category 改变时重新运行 effect
const onClickHandler = (e: React.MouseEvent) => {
// 使用 e.currentTarget.value 获取 button 的值
setCategory(e.currentTarget.value);
};
return (
菜品分类
-
海鲜 (Seafood)
-
素食 (Vegetarian)
-
甜点 (Dessert)
{loading && 加载中...
}
{error && {error}
}
{!loading && !error && meals.length === 0 && 未找到相关菜品。
}
{!loading && !error && meals.length > 0 && (
{category} 菜品:
{meals.map((meal: any) => (
- {meal.strMeal}
))}
)}
);
}
export default CategoryFilter; 注意事项:
如果出于某种设计或结构上的考虑,你坚持要让
代码示例:
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
function CategoryFilterWithDataAttribute() {
const [category, setCategory] = useState("Seafood"); // 初始分类
const [meals, setMeals] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!category) return;
setLoading(true);
setError(null);
axios
.get
(`${API_BASE_URL}${category}`)
.then(function (response) {
setMeals(response.data.meals || []);
})
.catch(function (err) {
console.error("API Error:", err);
setError("加载数据失败,请稍后再试。");
setMeals([]);
})
.finally(() => {
setLoading(false);
});
}, [category]);
const onClickHandler = (e: React.MouseEvent) => {
// 使用 e.currentTarget.getAttribute("data-value") 获取自定义数据
const clickedCategory = e.currentTarget.getAttribute("data-value");
if (clickedCategory) {
setCategory(clickedCategory);
}
};
return (
菜品分类 (使用 data-value)
-
海鲜 (Seafood)
-
素食 (Vegetarian)
-
甜点 (Dessert)
{loading && 加载中...
}
{error && {error}
}
{!loading && !error && meals.length === 0 && 未找到相关菜品。
}
{!loading && !error && meals.length > 0 && (
{category} 菜品:
{meals.map((meal: any) => (
- {meal.strMeal}
))}
)}
);
}
export default CategoryFilterWithDataAttribute; 注意事项:
在React应用中实现动态API调用时,选择正确的HTML元素和属性至关重要。
通过遵循这些最佳实践,你可以构建出更健壮、更易维护且用户体验更好的React应用。