当我点击加载更多按钮时,会出现新的数据,但图片仍然是固定的



我正在为星际飞船准备一个react项目。当用户单击"加载更多"按钮时,我希望第二页上的数据出现,并加载这些船只的图像。

目前,船名正在更改,但我的图像没有。我该怎么办?

这些是我在App.js中的代码;

import React, {Component} from 'react';
import "../styles/Films.css";
class Films extends Component {
state = {
data: [],
movieDetailsOpen: false,
movieSelected: "",
index: 0,
page: 1,
isLoading: false,
};
posterImages = [
"CR90-Corvette.png",
"stardestroyer.png",
"Sentinel-class-landing-craft.jpg",
"Death-Star.png",
"Millenium_Falcon.jpg",
"Y-wing.png",
"x-wing.png",
"TIE-Advanced-x1.png",
"executor.png",
"rebel-transport.png",
"rebel-transport.png",
"rebel-transport.png",
"rebel-transport.png"
];
async getFilms() {
const {page} =this.state
let data = [];
this.setState({
data: []
});
await fetch(`https://swapi.dev/api/starships/?page=${page}`)
.then(async (res) => {
let response = await res.json();
data = [...data, response.results];
console.log(data);
})
.catch(err => {
console.log(err);
});
data[0].map((res, index) => {
this.setState({
data: [...this.state.data, res]
});
return res;
});
}
componentWillMount() {
this.getFilms();
}
componentDidMount() {
const { page } = this.state;

}
componentDidUpdate(prevProps,prevState) {
if (prevState.page !== this.state.page) {
this.getFilms();
}
}
loadMore = () => {
this.setState((prevState) => ({
page: prevState.page + 1
}));
}; 
render() {
const {isLoading} = this.state;
return (

<div className="starships-wrapper">
<div className="top" id="top">
<img src="./logo.png" alt="logo"/>
</div>
<div className="bottom" id="bottom">
<ul>
{this.state.data.map((res, index) => {
return (
<li key={index}
className="ship-list"
style={{backgroundImage: `url(${this.posterImages[index]})`}}
>
<div className="name">{res.name}</div>
</li>
)
}
)}
</ul>
</div>
<div className="load-more">
<button onClick={this.loadMore} className="btn-grad" variant="dark">
{isLoading ? 'Loading...' : 'Load More'}
</button>


</div>
</div>
)


}
}
export default Films;

Poster图像不会更改,因为数组没有更改。它是硬编码的。所以我不确定你期望改变什么。

相关内容

最新更新