我正在学习如何从Reaction中调用RESTAPI,并且对在异步函数中调用Reaction时会发生什么感到困惑.在下面的组件中,我们看到在fetchPlaces
函数的第一行中,我们调用setIsFetching()
状态为真.
import { useState, useEffect } from "react";
import Places from "./Places.jsx";
import Error from "./Error.jsx";
import { sortPlacesByDistance } from "../loc.js";
import { fetchAvailablePlaces } from "../http.js";
export default function AvailablePlaces({ onSelectPlace }) {
const [isFetching, setIsFetching] = useState(false);
const [availablePlaces, setAvailablePlaces] = useState([]);
const [error, setError] = useState();
useEffect(() => {
async function fetchPlaces() {
setIsFetching(true);
try {
const availablePlaces = await fetchAvailablePlaces();
setAvailablePlaces(sortedPlaces);
setIsFetching(false);
});
} catch (error) {
setError({
message:
error.message || "Could not fetch places, please try again later.",
});
setIsFething(false);
}
}
fetchPlaces();
}, []);
if (error) {
return <Error title="An error occurred!" message={error.message} />;
}
return (
<Places
title="Available Places"
places={availablePlaces}
isLoading={isFetching}
loadingText="Fetching place data..."
fallbackText="No places available."
onSelectPlace={onSelectPlace}
/>
);
}
我这里的问题是,Reaction是否等待状态更新,直到整个函数完成?或者它会更新状态,因为它是一个异步函数,然后再次重新呈现组件?如果是,原因何在?
我猜我很困惑,因为在其他函数中,例如:
function a() {
setIsFetching(true)
// .... a lot more logic is done below
}
是否要等到a
运行完成后才进行react ,以更新状态并重新呈现组件?为什么使用Async函数时,在函数运行之前更新状态?我认为它会等待整个函数执行,因为我们有AWait关键字