为什么不是按排序顺序渲染的数据

发布于 2025-02-07 01:49:42 字数 3137 浏览 2 评论 0原文

为什么不按排序顺序渲染的数据

我将游乐设施作为近乎; 。

但是,为什么分类器未排序呢?

排序之前是否会呈现排序?如果是这样,我该如何在渲染之前对乘车进行排序?

Rides.js

import { useEffect, useState } from "react";
import Navbar from "./Navbar";
import NearestRides from "./NearestRides";

const Rides = () => {
  const [rides, setRides] = useState([]);
  const [user, setUser] = useState({});


  useEffect(() => {
    const fetchRides = async () => {
      const data = await fetch('https://assessment.api.vweb.app/rides');
      const json = await data.json();
      setRides(json);
    }

    const fetchUser = async () => {
      const data = await fetch('https://assessment.api.vweb.app/user');

      const json = await data.json();
      console.log(json);
      setUser(json);
    }
    
    const makeNetworkCalls = async() => {
      await fetchRides();
      await fetchUser();
    }

    makeNetworkCalls().catch((e) => {
      console.log(e);
    })

  }, [])

  useEffect(() => {
    const calculateDistance = async(path, user_station) => {
      let min = Math.abs(user_station - path[0]);
      for(let i = 0; i<path.length; i++){
        if(path[i] === user_station){
          return 0;
        }
        if(Math.abs(path[i] - user_station) < min){
          min = Math.abs(path[i] - user_station);
        }
      }
      return min;
    }

    const updaterides = async () => {
      rides.map(async (ride) => {
        ride.distance = await calculateDistance(
          ride.station_path,
          user.station_code
        );
      });
    };

    if (rides?.length > 0) {
      updaterides().catch((e) => {
        console.log(e);
      });
    }
  }, [rides,user]);

  return (
    <div>
      <Navbar user = {user}/>
      <div className="home">
        <NearestRides rides = {rides}/>
      </div>
    </div>
  );

}

export default Rides;

newStrides.js

import { useEffect, useState } from "react";

const NearestRides = ({rides}) => {
  const [sortedRides, setSortedRides] = useState([]);

  useEffect(() => {
    const sortRides = async() => {
      const sorted = await rides.sort((ride1,ride2) => {
        return ride1.distance > ride2.distance ? 1 : -1;
      })

      setSortedRides(sorted);
    }

    sortRides().catch((e) => console.log(e));

  }, [rides]);

  return(
    <div className="rides">
      {console.log(sortedRides)}
      {sortedRides?.map((ride) => {
        return (
          <div className="ride-detail">
          <img src={ride.map_url} alt="Ride_map" />
          <div>
            <p>Ride Id : {ride.id}</p>
            <p>Origin Station : {ride.origin_station_code}</p>
            <p>Station Path : {ride.station_path}</p>
            <p>Date : {ride.date}</p>
            <p>Distance : {ride.distance}</p>
          </div>
        </div>
        )
      })}
    </div>
  )
}

export default NearestRides;

Why isn't the rendered data in sorted order

I am passing rides as a prop in the NearestRides component and inside the NearestRides component, first i am sorting the rides and setting to sortedRides and then i am mapping sortedRides.

but why is the sortedRides not sorted?

is sortedRides getting rendered before getting sorted? if so, how do i sort rides before rendering?

Rides.js

import { useEffect, useState } from "react";
import Navbar from "./Navbar";
import NearestRides from "./NearestRides";

const Rides = () => {
  const [rides, setRides] = useState([]);
  const [user, setUser] = useState({});


  useEffect(() => {
    const fetchRides = async () => {
      const data = await fetch('https://assessment.api.vweb.app/rides');
      const json = await data.json();
      setRides(json);
    }

    const fetchUser = async () => {
      const data = await fetch('https://assessment.api.vweb.app/user');

      const json = await data.json();
      console.log(json);
      setUser(json);
    }
    
    const makeNetworkCalls = async() => {
      await fetchRides();
      await fetchUser();
    }

    makeNetworkCalls().catch((e) => {
      console.log(e);
    })

  }, [])

  useEffect(() => {
    const calculateDistance = async(path, user_station) => {
      let min = Math.abs(user_station - path[0]);
      for(let i = 0; i<path.length; i++){
        if(path[i] === user_station){
          return 0;
        }
        if(Math.abs(path[i] - user_station) < min){
          min = Math.abs(path[i] - user_station);
        }
      }
      return min;
    }

    const updaterides = async () => {
      rides.map(async (ride) => {
        ride.distance = await calculateDistance(
          ride.station_path,
          user.station_code
        );
      });
    };

    if (rides?.length > 0) {
      updaterides().catch((e) => {
        console.log(e);
      });
    }
  }, [rides,user]);

  return (
    <div>
      <Navbar user = {user}/>
      <div className="home">
        <NearestRides rides = {rides}/>
      </div>
    </div>
  );

}

export default Rides;

NearestRides.js

import { useEffect, useState } from "react";

const NearestRides = ({rides}) => {
  const [sortedRides, setSortedRides] = useState([]);

  useEffect(() => {
    const sortRides = async() => {
      const sorted = await rides.sort((ride1,ride2) => {
        return ride1.distance > ride2.distance ? 1 : -1;
      })

      setSortedRides(sorted);
    }

    sortRides().catch((e) => console.log(e));

  }, [rides]);

  return(
    <div className="rides">
      {console.log(sortedRides)}
      {sortedRides?.map((ride) => {
        return (
          <div className="ride-detail">
          <img src={ride.map_url} alt="Ride_map" />
          <div>
            <p>Ride Id : {ride.id}</p>
            <p>Origin Station : {ride.origin_station_code}</p>
            <p>Station Path : {ride.station_path}</p>
            <p>Date : {ride.date}</p>
            <p>Distance : {ride.distance}</p>
          </div>
        </div>
        )
      })}
    </div>
  )
}

export default NearestRides;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天邊彩虹 2025-02-14 01:49:42

看起来像是在计算距离并将距离属性添加到R​​ides数组中时,您实际上并未再次将其设置为rides使用setrides 。

因此,距离绝不是Rides数组中的一部分。 。

但是,将乘车设置为使用DEPS的使用效应将产生无限环路。

因此,建议在没有deps的情况下计算使用效果的距离 - 即在您获取骑行后立即。

It looks like that when you are calculating the distance and adding the distance property to rides array, you are not actually setting it again to the rides using setRides.

And so, the distance is never part of the rides array when received in child nearestRides and hence sorting method is not working in nestedRides.

But setting the rides in the useEffect with deps will create infinite loop.

So suggest to calculate the distance in the useEffect with no deps - ie right after you fetch the rides.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文