问题描述
这有点棘手,但仅在可用时才需要设置动画:
animate={recipes.length > 0 && "visible"}
animate="visible"
然后,在recipes
异步调用之后更新时,您不会再次触发动画。
const container = {
hidden: { opacity: 1, scale: 0 },
visible: {
opacity: 1,
scale: 1,
transition: {
staggerChildren: 0.5
}
}
};
const item = {
hidden: { x: 100, opacity: 0 },
visible: {
x: 0,
opacity: 1
}
};
const request = `https://www.themealdb.com/api/json/v1/1/search.PHP?s=chicken`;
function App() {
const [recipes, setRecipes] = useState([]);
useEffect(() => {
const getRecipes = async () => {
const response = await fetch(request);
const data = await response.json();
setRecipes(data.meals);
console.log(data.meals);
};
getRecipes();
}, []);
return (
<div className="App">
<motion.ul
variants={container}
initial="hidden"
animate={recipes.length > 0 && "visible"}
>
{recipes.map(recipe => (
<motion.li key={recipe.idMeal} variants={item}>
<RecipeCard title={recipe.strMeal} />
</motion.li>
))}
</motion.ul>
</div>
);
}
解决方法
我正在使用成帧器运动,并且试图达到交错效果,以便每个下一个孩子都有一些不错的延迟。有一条至关重要的代码行,其中当我突然替换[0,1,2,3].map
为recipes.map
所有子级时,它们被视为一个巨大的块,并且它们不会错开。
只需查看此演示,您肯定会知道我的意思。此代码有什么问题?我迷失了方向:)
function App() {
const request = `https://www.themealdb.com/api/json/v1/1/search.php?s=chicken`;
const [recipes,setRecipes] = useState([]);
useEffect(() => {
getRecipes();
},[]);
const getRecipes = async () => {
const response = await fetch(request);
const data = await response.json();
setRecipes(data.meals);
console.log(data.meals);
};
const container = {
hidden: { opacity: 1,scale: 0 },visible: {
opacity: 1,scale: 1,transition: {
when: "beforeChildren",staggerChildren: 0.5
}
}
};
const item = {
hidden: { x: 100,opacity: 0 },visible: {
x: 0,opacity: 1
}
};
return (
<div className="App">
<motion.ul variants={container} initial="hidden" animate="visible">
{[0,3].map(recipe => (
<motion.li key={recipe.idMeal} variants={item}>
<RecipeCard title={recipe.strMeal} />
</motion.li>
))}
</motion.ul>
<motion.ul variants={container} initial="hidden" animate="visible">
{recipes.map(recipe => (
<motion.li key={recipe.idMeal} variants={item}>
<RecipeCard title={recipe.strMeal} />
</motion.li>
))}
</motion.ul>
</div>
);
}