在我的函数中,我可以从状态遍历列表,但是当我要在渲染中进行映射时不起作用
class DesktopList extends Component {
constructor(props) {
super(props);
this.state = {
items: [
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/765356/765356._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/232863/232863._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/779028/779028._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/765281/765281._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/495991/495991._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/694446/694446._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/460929/460929._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/755543/755543._SX1280_QL80_TTD_.jpg",
"https://images-na.ssl-images-amazon.com/images/S/cmx-images-prod/Item/756917/756917._SX1280_QL80_TTD_.jpg",
],
posters: []
}
}
sortIntoArray = () => {
let posterImages = [...this.state.items];
const size = 5;
const result = this.state.posters;
for (var i=0;i<posterImages.length;i+=size)
result.push( posterImages.slice(i,i+size) )
this.setState({posters: result})
let images = this.state.posters
images[0].map(item => console.log(item.poster))
}
render() {
let {posters} = this.state;
let poster = posters[0].map((item, index) =>
<img src={item.poster} alt="poster" style={style.poster} key={index}/>
)
return (
<div
style={style.posterList} className="posterlist">
{poster}
</div>
);
}
}
我希望每个海报都从第一个数组开始显示
这就是我得到的
TypeError:海报[0]未定义
答案 0 :(得分:-1)
在执行让{posters} = this.state; 之前,您需要调用您的 sortIntoArray()。您需要确保从中分配要分配的值(无论是状态还是其他任何值)。但是,从您的代码state.posters是未定义的,因此您的可变海报是未定义的。
很难给出确切的配方,因为它取决于组件的整体。