在React中,是否有方法将API数据从一个文件导入到另一个文件



所以我正在开发这个应用程序,只要你搜索一个鞋品牌,它就会带你进入一个页面,为你提供该品牌不同类型鞋的网格。

这是位于searchBar.js文件中的API搜索栏函数:


function SearchBar() {
const [isLoaded, setIsLoaded] = useState(false);
const [brand, setBrand] = useState("");
const [sneakers, setSneakers] = useState({});
const [redirect, setRedirect] = useState(false)
const brandsList = [
{ brandName: "Adidas" },
{ brandName: "Asics" },
{ brandName: "Converse" },
{ brandName: "Jordan" },
{ brandName: "New Balance" },
{ brandName: "Nike" },
{ brandName: "Puma" },
{ brandName: "Reebok" },
{ brandName: "Saucony" },
{ brandName: "Under Armour" },
{ brandName: "Vans" }
]
const defaultBrands = {
options: brandsList,
getOptionLabel: (option) => option.brandName,
};

const search = (evt) => {
if (evt.key === "Enter") {
fetch(
`https://api.thesneakerdatabase.com/v1/sneakers?limit=10&brand=${brand}`
)
.then((res) => res.json())
.then((result) => {
setIsLoaded(true);
setBrand("");
setSneakers(result);
console.log(result.results);
setRedirect(true)
});
}
};
return (
<div>
<div>
{
redirect ? <Redirect to="/allShoes:id" /> : <div className="brand-search">
<div className="search-box col">
<Autocomplete
{...defaultBrands}
id="auto-complete"
autoComplete
includeInputInList
renderInput={(params) =>
<TextField {...params}
placeholder="Search brand..."
margin="normal"
onChange={(e) => setBrand(e.target.value)}
value={brand}
onKeyPress={search}
/>}
/>
</div>
</div>
}
</div>
</div>
)
}
export default SearchBar;

当你搜索一个品牌时,我试图将api数据放入allShoes.js文件:


import React from "react";
import { MDBContainer, MDBRow, MDBCol, MDBCard, MDBCardImage, MDBCardBody, MDBCardTitle, MDBCardFooter, MDBCardText } from "mdbreact";
import FavoriteIcon from '@material-ui/icons/Favorite';
import NotesIcon from '@material-ui/icons/Notes';
import "../allShoes/allShoes.css";

function gridTable(props) {
return (

<div>

<MDBContainer style={{textAlign:"center", marginTop:"8%"}}>

<h2>View All Shoes</h2>
<MDBRow style={{padding: "6%"}}>
<MDBCol size="3">
<MDBCard narrow ecommerce className='mb-2'>
<MDBCardTitle>
<strong>
{/* {name} */}
</strong>
</MDBCardTitle>
<MDBCardImage
cascade
top
src='https://static.nike.com/a/images/f_auto/q_auto:eco/t_PDP_864_v1/eric5lwitzffpoisq0rj/blazer-mid-77-vintage-mens-shoe-flCCX4.jpg'
alt='shoe photo'
/>
<MDBCardBody cascade>
<MDBCardFooter className='px-1'>
<span className='float-left'>
{/* {title} */}
</span>
<span className='float-right'>
<FavoriteIcon></FavoriteIcon>
<NotesIcon></NotesIcon>
</span>
</MDBCardFooter>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>

</div>
);
}
export default gridTable;

一种方法可以是移动鞋数据,并使用setter函数将鞋数据设置在SearchBar之外。最好使用ContextAPI,在下游共享它,以便使这些对包括gridTable在内的所有组件都可用。

此外,在重定向时,您可以在url中传递品牌id,以筛选出allBrands页面中的其他品牌。

相关内容

最新更新