![](/img/trans.png)
[英]How to map over an array and pass it as props to child component correctly in React?
[英]How to pass an array as props in React component and use map on it?
我正在開發一個具有搜索欄的應用程序 - 當用戶輸入某些內容時,會進行 API 調用,並且 json 正在被發回。 在下面的代碼中,一個名為 sampleList 的數組表示這個 json。 然后將 json 傳遞給 List 組件以呈現一個簡單的列表。 這就是我所做的,但是它不起作用。 我是反應的初學者,我有兩個主要問題:
這是代碼:Searchbar.tsx
const sampleList = [
{ id: 1, name: "a"},
{ id: 2, name: "b"},
];
const Searchbar = () => {
const onSubmit = (e) => {
sampleList = getJson();
}
return (
<form className="search-form" onSubmit={onSubmit}>
<input type="text"></input>
<input type="submit"></input>
</form>
<List prop={sampleList}/>
)}
列表.tsx
const List = ({sampleList}) => {
return(
<div>
sampleList.map((item, index) =>
<div key={item.id}>
{item.name}
</div>
)
</div>
)}
任何幫助將不勝感激。
const List = ({ prop }) => {
return(
<div>
prop.map((item, index) =>
<div key={item.id}>
{item.name}
</div>
)
</div>
)}
prop
屬性將是您的simpleList
值的關鍵。 您的List
組件的參數將是 json object ,其中包含鍵和值作為您的prop
鍵。 例如,您還可以將prop
屬性的名稱更改為放置list
。
如果您想在用戶單擊搜索按鈕時顯示列表組件,您可以使用state
屬性。 我希望這個鏈接對你有幫助: https://reactjs.org/docs/state-and-lifecycle.html
理想情況下,您需要在 Searchbar 中維護兩種狀態。
簡而言之,每當更新 state 時,組件將重新渲染和水合 state 中存在的新值。
const Searchbar = () => {
const [searchResults, setSearchResults] = useState([]);
const [searchComplete, setSearchComplete] = useState(false);
const onSubmit = async (e) => {
const sampleList = await getJson();
setSeatchResults(sampleList); // This will cause a state update and then pass the property along to the list component
setSearchComplete(true); // This enable showing the list component now that the search is complete
};
return (
<form className="search-form" onSubmit={onSubmit}>
<input type="text"></input>
<input type="submit"></input>
</form>
{ searchComplete && <List prop={searchResults} /> }
);
}
至於列表組件,您的代碼看起來還不錯。 您只需將 sampleList 重命名為 prop,因為您在上述組件中將搜索結果作為 prop 傳遞
const List = ({prop}) => {
return (
<div>
prop.map((item, index) =>
<div key={item.id}>
{item.name}
</div>
)
</div>
);
};
一條建議,在調用 api 時始終使用 async-await。 並確保良好的錯誤處理以避免所有情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.