问题描述
我的 React 应用中有一些自定义组件,它们从外部 API 获取数据以在我的应用中显示信息。
我正在尝试找出将加载状态从我的子组件传递到父组件的最佳方式。
这是我的 App.js:
const App = () => {
return (
<div className="App">
<Loader show={loading} />
<Navbar />
<Main />
</div>
);
}
export default App;
这是我的 Main.js:
const Main = () => {
const [ images,setimages ] = useState([]);
const [ loading,setLoading ] = useState(false);
useEffect(() => {
const getFeed = async () => {
setLoading(true);
const response = await fetch(`https://localhost/api/Feed`);
const data = await response.json();
const results = data.data.results;
setimages(results);
setLoading(false);
}
getFeed();
},[]);
return (
<Grid container spacing={2} className="media">
{
images.map((image,index) => {
return (
<Grid container item xs={6} sm={3} md={2}>
<ImageItem key={ `image_${ index }` } details={ image } />
</Grid>
);
})
}
</Grid>
);
}
export default Main;
如何从我的 loading
组件中的 Main
组件获取 App
状态?
解决方法
试试这个:
应用程序。 js
- 您应该在 App.js 中创建
loading
状态
const App = () => {
const [ loading,setLoading ] = useState(false);
return (
<div className="App">
<Loader show={loading} />
<Navbar />
<Main setLoading={setLoading} />
</div>
);
}
export default App;
Main.js
- 将
setLoading
作为道具传递给 Main 组件并接收它。
const Main = ({setLoading} ) => {
const [ images,setImages ] = useState([]);
useEffect(() => {
const getFeed = async () => {
setLoading(true);
const response = await fetch(`https://localhost/api/feed`);
const data = await response.json();
const results = data.data.results;
setImages(results);
setLoading(false);
}
getFeed();
},[]);
return (
<Grid container spacing={2} className="media">
{
images.map((image,index) => {
return (
<Grid container item xs={6} sm={3} md={2}>
<ImageItem key={ `image_${ index }` } details={ image } />
</Grid>
);
})
}
</Grid>
);
}
export default Main;
就这些
,如果 Loading 组件除了显示一些加载 ui 之外什么都不做,请将其向下移动到 Main 组件,以便它可以直接访问加载状态。
所以你可能会在渲染中得到这样的东西
<>
<Loading show={loading} />
<Grid container spacing={2} className="media">
{
images.map((image,index) => {
return (
<Grid container item xs={6} sm={3} md={2}>
<ImageItem key={ `image_${ index }` } details={ image } />
</Grid>
);
})
}
</Grid>
</>