我正在使用react-router-dom,并且试图在我的“图库”页面中进行延迟加载,但是当我访问图库页面时,所有图像均已加载,并且延迟加载无法正常工作。最初,我在没有react-router-dom的情况下尝试了它,并且效果很好。所以我觉得问题出在路由上。
./App.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Gallery from "./Gallery";
import Home from "./Home";
function App() {
return (
<Router>
<Switch>
<Route path="/gallery" render={() => <Gallery />} />
<Route path="/" render={() => <Home />} />
</Switch>
</Router>
);
}
export default App;
./Gallery.js
import React from "react";
import "./App.css";
import Amplify, { Auth, Storage } from "aws-amplify";
import config from "./aws-exports";
import LazyLoad from "react-lazyload";
Amplify.configure(config);
const getCreds = async () => {
let creds = await Auth.currentCredentials();
};
getCreds();
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
images: []
};
}
async componentDidMount() {
await Storage.list("")
.then(res => {
res.shift(); //remove the first element of the array
res.map(imgObject => {
let lnk =
"LINK IM FETCHING FROM" + imgObject.key;
this.setState(prevState => ({
images: [...prevState.images, lnk]
}));
return imgObject;
});
})
.catch(err => console.log(err));
}
render() {
const items = this.state.images.map(imgLink => (
<LazyLoad height={200} key={Math.random()}>
<img width={1080} src={imgLink} alt="img" />
</LazyLoad>
));
return <div className="App">{items}</div>;
}
}
export default App;
当我使用与<Router>
相同的代码删除<Switch>
和./Gallery.js
时,延迟加载按预期方式工作