我有一个反应页面,其中使用api获取数据。所有数据都已成功获取,但无法获取图像数组。我为此编写的代码是
import React, {Component} from 'react';
export default class RoomDetail extends Component{
constructor(props){
super(props);
this.state = { rooms:[] }
}
componentDidMount(){
console.log('componentDidMount');
console.log(this.props.data.slug);
this.loadRoomFromServer();
}
loadRoomFromServer(){
$.ajax({
url:'/api/v1/rental/'+this.props.data.slug,
dataType:'json',
success: (data) => {
console.log('data',data);
this.setState({rooms: data});
},
error: (xhr, status, err) => {
console.error(url, status, err.toString());
}
});
}
render() {
if(this.state.rooms.gallery){
console.log(this.state.rooms.gallery);
let imageFile = this.state.rooms.gallery.map((image) => {
return(
<img src={image.image} className="img-responsive" />
);
});
}
if(this.state.rooms){
console.log('rooms',this.state.rooms);
return (
<div className="container-fluid">
<div className="row">
<div className="col-sm-12">
<img src="" />
</div>
</div>
<div className="col-md-6">
<ul className="list-group">
<li>Listing Name</li>
<li>Summary on Listing</li>
<li>Property Type</li>
<li>No of Rooms</li>
<li>Gallery</li>
</ul>
</div>
<div className="col-md-6">
<ul className="list-group">
<li>{this.state.rooms.listingName}</li>
<li>{this.state.rooms.summary}</li>
<li>{this.state.rooms.property}</li>
<li>{this.state.rooms.room}</li>
<li>{this.state.rooms.amenities}</li>
</ul>
</div>
</div>
);
}
else{
return <li>Nothing to display</li>
}
}
}
如何显示所有图像?如果我在this.state.rooms.amenities之后使用变量imageFile,我会收到一条错误,指出未定义imageFile。 imageFile未加载,因此可能说未定义。
答案 0 :(得分:1)
这不是React特有的,它只是简单的javascript。 let
关键字定义了一个块范围的变量,即它只存在于它所在的if
语句中。如果您希望它在其他地方可用,您应该在if:
let imageFile; // Define the variable outside of the if statement
if(this.state.rooms.gallery){
console.log(this.state.rooms.gallery);
// Dump the `let` keyword inside of the if statement
imageFile = this.state.rooms.gallery.map((image) => {
// ...
});
}
if (this.state.rooms) {
// Now `imageFile` can be accessed here too
}
由于第一个if语句检查第二个属性,我宁愿将其合理化为:
if (this.state.rooms) {
let imageFile;
if (this.state.rooms.gallery) {
// Assign `imageFile here`
}
}