当数据加载到 useState 时,我的组件在页面加载后进行动画处理

My component is animating after page load when the data is loaded in the useState

我正在使用 useState() 在安装组件之前加载一些数据。

  const [leaderboardData, setLeaderboardData] = useState([]);
  const [featuredSelectedItem, setSelectedItem] = useState({});
  useEffect(() => {
    let dummyData = [
      ..someData
    ]
    //Order based on standings
    dummyData.sort((a, b) => {
      return a.current_season_standing - b.current_season_standing;
    });

    dummyData[0].active = true;
    setSelectedItem(dummyData[0]);
    setLeaderboardData(dummyData);
  }, []);

我的组件包装在一个过渡组中。

     <div className="d-flex h-100 home_container">
      <TransitionGroup className="p-5 flex-1 home_selected_user">
        <SwitchTransition>
          <CSSTransition
            key={featuredSelectedItem.id}
            timeout={500}
            classNames="featuredItem"
          >
            <div>
              <img src="https://via.placeholder.com/150" alt={featuredSelectedItem.name} />
              <h1>{featuredSelectedItem.name}</h1>
              <p>Rank: {featuredSelectedItem.current_season_standing}</p>
              <p>Country: {featuredSelectedItem.country}</p>
              <p>Handicap: {featuredSelectedItem.handicap}</p>
              <p>Wins: {featuredSelectedItem.wins}</p>
              <p>View Player Profile</p>
            </div>
          </CSSTransition>
        </SwitchTransition>
      </TransitionGroup>
      <div className="home_leaderboard p-4 flex-1">
        <Leaderboard activeHandler={activeLeaderboardHandler} data={leaderboardData}></Leaderboard>
      </div>
     </div>

在页面加载时,组件加载时不加载任何数据,然后在数据加载到组件上后进行动画处理。我的目标是在加载页面之前将数据加载到组件上,以便不会触发转换?

My component is animating after page load when the data is loaded in the useState

那是因为 useEffect() 将在每次渲染后 运行 。在你的 useEffect() 里面你有 setSelectedItem().

My goal is for the data to be loaded on the component before the page is loaded so the transition does not trigger?

如果你想之前有它,将数据作为道具传递。然后使用条件渲染 featuredSelectedItem.

function SomeComponent(props) {
  // initialize using props
  const [featuredSelectedItem, setSelectedItem] = useState(props.data);

  return (
    featuredSelectedItem.length > 0 &&
      <TransitionGroup>...</TransitionGroup>
  )
}

// Usage:
const dummyData = [...someData]

// pass dummyData as prop
<SomeComponent data={dummyData} />