问题
I am using framer motion and I am trying to achieve stagger so that every next child has some nice delay. There is one crucial line of code in which when I replace [0, 1, 2, 3].map
with recipes.map
suddenly all of the children are treated as one huge block and they do not stagger.
Just check out this demo and you will surely know what I mean. What is wrong with this code? I am losing my mind :)
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, 1, 2, 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>
);
}
回答1:
Its a bit tricky, but you need to animate only when the items are available:
animate={recipes.length > 0 && "visible"}
That's because on the first render you actually animate an empty array.
animate="visible"
Then, when you update the recipes
after the async call, you don't trigger the animation again.
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>
);
}
来源:https://stackoverflow.com/questions/62602351/why-does-array-map-and-0-1-2-map-in-react-work-in-different-way