使用两个使用效果,但组件仅执行第一个后返回
在渲染(骑行组件的内部return())上,ride.distance是不确定的,但是当在打印每个乘车时,在二次使用效果时,它们具有乘车
。第二次使用效应以后运行还是还有其他问题?
在渲染第二种使用效果完成之前,如何实现这一目标?
import Navbar from "./Navbar";
const Rides = () => {
const [rides, setRides] = useState([]);
const [user, setUser] = useState({});
const [updatedRides, setUpdatedRides] = useState([]);
useEffect(() => {
const fetchRides = async () => {
const data = await fetch('https://assessment.api.vweb.app/rides');
const json = await data.json();
setRides(json);
console.log(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() => {
setUpdatedRides(rides);
updatedRides.map(async(ride) => {
ride.distance = await calculateDistance(ride.station_path, user.station_code);
console.log(ride);
})
}
updaterides().catch((e) => {
console.log(e);
})
}, [rides]);
return(
<div>
<Navbar user = {user}/>
<div className="rides">
{updatedRides.map((ride) => {
return (
<div className="rideDetail">
<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>
</div>
)
}
export default Rides;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我修复了您的代码,请在此处查看。问题与非代码>异步行为有关。在您的第二个
中使用
fordeffect 函数,您正在设置UpdateDrides
您正在映射它,但是它不按照您的预期工作,因为>状态
更改在MAP
之前没有立即更新。I fixed your code check it out here https://codesandbox.io/embed/busy-payne-qiiw5r?fontsize=14&hidenavigation=1&theme=dark . Problem was related with non
async
behaviour. In your seconduseEffect
insideupdaterides
function, you are settingupdatedRides
then you are mapping it but it does not work as you expected sincestate
changes are not updating immediately beforemap
.