如何避免在反作用力弹簧中产生波纹弹簧

时间:2020-04-07 05:10:49

标签: reactjs react-spring

我正在创建一个“伪”堆栈视图组件,我有一个ID数组,其中每个ID会将复杂的内容加载到Card中,所以我想要的是预加载2张Card,然后在每次单击时附加一张新卡,这样我就可以享受更舒适的滑入体验。

我不使用useTransition,因为每张卡都将被延迟安装,并且体验不流畅(由于安装时间而定)。

我已经有了想要的东西,但是我正在创建浪费的弹簧(请参阅控制台日志),这是我发现为每个附加卡创建新弹簧的唯一方法,以前的弹簧“记住”了当前位置,我无法重复使用它们

有没有更好的方法来实现这一目标?

codesandbox:https://codesandbox.io/s/jolly-stonebraker-fjd19?file=/src/App.jsx

import React, { useState, useEffect } from "react";
import { useSpring, animated, useSprings } from "react-spring";
import "./styles.css";
import Card from "./Card";

let data = [];
for (let i = 0; i < 50; i++) {
  data.push(i);
}

export default function App() {
  const [currentData, setCurrentData] = useState([data[0], data[1]]);
  const [currentIndex, setCurrentIndex] = useState(0);

  const [springs, set] = useSprings(currentData.length, idx => {
    const isLast = idx === currentData.length - 1;
    console.log("init uses spring");
    return {
      from: { x: isLast ? 300 : 0 },
      onRest: () => {
        console.log("on reset");
        setCurrentIndex(currentIndex + 1);
        const newArr = [...currentData];
        newArr.push(data[currentIndex + 2]);
        newArr[currentIndex] = null;
        setCurrentData(newArr);
      }
    };
  });

  // const springs = [goAwayProps, slideInProps];

  useEffect(() => {
    console.log("mount");
  }, []);

  const handleNext = () => {
    // setCurrentData([data[currentIndex + 1], data[currentIndex + 2]]);
    set(idx => {
      const isLast = idx === currentData.length - 1;
      return {
        to: async next => {
          await next({
            x: isLast ? 0 : -80
          });
        }
      };
    });
  };

  console.log(currentData);
  return (
    <div className="App">
      <button onClick={handleNext}>next</button>
      <div className="container">
        {currentData.map((d, i) => {
          if (d === null) return null;
          const { x } = springs[i];
          return (
            <animated.div
              style={{
                transform: x.interpolate(x => `translate3d(${x}px,0,0)`)
              }}
            >
              <Card>{d}</Card>
            </animated.div>
          );
        })}
      </div>
    </div>
  );
}

0 个答案:

没有答案