1

我正在使用成帧器运动,并且我正在尝试实现交错,以便每个下一个孩子都有一些不错的延迟。有一个关键的代码行,当我突然替换时[0, 1, 2, 3].maprecipes.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, 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>
  );
}
4

1 回答 1

4

它有点棘手,但您只需要在项目可用时制作动画:

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>
  );
}

编辑 eager-mestorf-i8y14

于 2020-06-27T16:56:33.513 回答