React-spring 动画仅在第一次渲染时有效

React-spring animation only works at first render

我尝试为数组中出现的新条目设置动画 react-spring 它在第一次渲染时工作得很好,但在更新时没有设置动画

这是一个代码沙箱,我在其中以一定间隔重现了该问题:https://codesandbox.io/s/01672okvpl

import React from "react";
import ReactDOM from "react-dom";
import { Transition, animated, config } from "react-spring";

import "./styles.css";

class App extends React.Component {
  state = { fake: ["a", "b", "c", "d", "e", "f"] };

  fakeUpdates = () => {
    const [head, ...tail] = this.state.fake.reverse();
    this.setState({ fake: [...tail, head].reverse() });
  };

  componentDidMount() {
    setInterval(this.fakeUpdates, 2000);
  }

  componentWillUnmount() {
    clearInterval(this.fakeUpdates);
  }

  render() {
    const { fake } = this.state;
    return (
      <div className="App">
        {fake.map((entry, index) => (
          <Transition
            native
            from={{
              transform: `translateY(${index === 0 ? "-200%" : "-100%"})`
            }}
            to={{ transform: "translateY(0)" }}
            config={config.slow}
            key={index}
          >
            {styles => <animated.div style={styles}>{entry}</animated.div>}
          </Transition>
        ))}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我尝试了 SpringTransition,结果相同。

您的问题是因为您的密钥没有更新。由于您将键 0 替换为键 0,它认为它已经应用了转换。

当改变key为${entry}_${index}时,它会更新他们的key为'a_0',然后是'f_0',它们是唯一和不同的,因此触发你想要的效果。

entry 单独作为键也不起作用,因为它已经存在于 DOM 中,所以它不会重新渲染过渡。

<Transition
  native
  from={{
    transform: `translateY(${index === 0 ? "-200%" : "-100%"})`
  }}
  to={{ transform: "translateY(0)" }}
  config={config.slow}
  key={`${entry}_${index}`}
>

在这里查看https://codesandbox.io/s/kkp98ry4mo