这应该为您解决问题,并且比您最初的反应更像。
api.js
import React, { useEffect, useState } from "react";
export default function useWrap(id) {
const [apiData, setApiData] = useState({});
const [error, setError] = useState(null);
useEffect(() => {
(async () => {
await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
.then(async (res) => await res.json())
.then((result) => setApiData(result))
.catch((err) => setError(err));
})();
}, [id]);
return error ? error : apiData;
}
ProfileDetail.js
import React from "react";
import useWrap from "./Api";
export default function ProfileDetails() {
const user = useWrap(1);
if (user === null) {
return;
}
return <div>{user.id}</div>;
}