[英]Calling and passing API data to other component in React.js
I want to call all API in Specific component "API.js", and I want to Share Json data to other components, in the below example I am using Promise to share JSON, but I want to share data without promises if it is possible然后告訴我?
API.js File
import axios from "axios";
export async function TabelData() {
return new Promise(async (resolve, reject) => {
var res;
console.log("Api Res=>", res);
try {
await axios({
method: "get",
url: "https://randomuser.me/api/?results=100",
}).then(function (response) {
res = response.data.results;
console.log("Api Res", response);
});
} catch (error) {
console.error(error);
}
resolve(res);
});
}
Search.js File
import { TabelData } from "../../../services/Api";
import "./Search.css";`enter code here`
const Search = () => {
const [userData, setUserData] = useState([]);
const [q, setQ] = useState("");
useEffect(() => {
TabelData().then((res) => {
setUserData(res);
});
}, []);
您可能想要簡化 TabelData function 如下所示:
export async function TabelData() {
try {
const response = await axios({
method: "get",
url: "https://randomuser.me/api/?results=100"
});
return response.data.results;
} catch (error) {
console.error(error);
}
}
有很多方法可以做到這一點,但您的主要目標是將結果存儲在提示 React 時不會重新渲染的東西中,例如 React 上下文(查看useContext )。 上下文允許您存儲任何內容並在任何子組件中檢索它們。
而且,我喜歡的一個庫通過緩存結果很好地做到了這一點,那就是react-query 。 您可以單獨使用 react-query,也可以與其他上下文一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.