gpt4 book ai didi

reactjs - 将子组件传递给 API 组件

转载 作者:行者123 更新时间:2023-12-04 07:51:43 24 4
gpt4 key购买 nike

我正在尝试将 API fetcher 实现为可重用组件,以减少重复代码。
如何将子组件传递给此 ApiFetcher,以便它呈现特定子组件而不是硬编码组件?
此外,我的 CompanyProfile 组件是否以有效的方式编码或是否有优化空间?

import React from "react";
import { useState, useEffect } from "react";

function ApiFetcher(props) {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);

useEffect(() => {
fetch(props.url)
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);

if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {

// TODO: return props.childrend instead of hard coded component

return (
<div>
<CompanyProfile items={items} />
</div>
);
}
}

function CompanyProfile(props) {
return (
<div>
<ul>
{props.items.map((item) => (
<li key={item.symbol}>
{item.companyName} {item.price}
</li>
))}
</ul>
</div>
);
}

function App() {
const apiUrl =
"https://financialmodelingprep.com/api/v3/profile/AAPL?apikey=demo";

// TODO: implement children of ApiFetcher
return (
<div>
<ApiFetcher url={apiUrl}>
</ApiFetcher>
</div>
);
}

export default App;

最佳答案

您可以提供一个函数作为 ApiFetcher 的唯一子项,并在加载数据后调用它:

<ApiFetcher url={apiUrl}>
{(items) => {
return <CompanyProfile items={items} />;
}}
</ApiFetcher>
然后在 ApiFetcher :
  if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
// Call the provided function
return props.children(items);
}

关于reactjs - 将子组件传递给 API 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66930228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com