我正在尝试将图像源链接播种到我的mongoDB中,然后将其拉入我的状态,然后我尝试加载图像。下面是我的种子和我的反应页面加载它。
数据库种子:
const houseSeed = [
{
name: "Scenic View",
address: "123 internet st",
imagesrc: "../client/src/images/house5.jpg",
about:
'This houses biggest selling point is the view from the wall size windows
put along the entire length off the house.',
date: new Date(Date.now())
},
{
name: "Modern Style",
address: "123 internet st",
imagesrc: "../client/src/images/house4.jpg",
about:
'This houses biggest selling point is the very modern approach to the
architecture of the home and the sleek clean lines it contains.',
date: new Date(Date.now())
}
];
将包含整个类的页面与状态和正在呈现的内容进行反应。尝试将state.source加载到:
class About extends Component {
state = {
house: {},
source: ""
};
componentDidMount() {
API.getHouse(this.props.match.params.id)
.then(res => this.setState({ house: res.data, source: res.data.imagesrc}))
.then(console.log("state source" + this.state.source))
.catch(err => console.log(err));
console.log("state source" + this.state.source);
}
imageFunct =() => {
return <img src={this.state.source} alt='image of house' />;
}
render(){
return(
<Container fluid>
<Row>
<Col size="md-12">
<Header />
<Nav />
</Col>
</Row>
<Row>
<Col size="md-3">
</Col>
<Col size="md-6">
<Row>
<Col size="md-12">
<h1>{this.state.house.name}</h1>
</Col>
</Row>
<Row>
<Col size="md-3" />
<Col size="md-6">
{this.imageFunct()}
</Col>
<Col size="md-3" />
</Row>
<Row>
<Col size="md-12">
<h4>{this.state.house.about}</h4>
</Col>
</Row>
</Col>
<Col size="md-3">
</Col>
</Row>
</Container>
)
}
它会显示图像alt而不是图像本身。
答案 0 :(得分:0)
这应该有效:
class About extends Component {
state = {
house: {},
source: ""
};
componentDidMount() {
API.getHouse(this.props.match.params.id)
.then(res => this.setState({ house: res.data, source: res.data.imagesrc}))
.then(console.log("state source" + this.state.source))
.catch(err => console.log(err));
console.log("state source" + this.state.source);
}
render(){
return(
<Container fluid>
<Row>
<Col size="md-12">
<Header />
<Nav />
</Col>
</Row>
<Row>
<Col size="md-3">
</Col>
<Col size="md-6">
<Row>
<Col size="md-12">
<h1>{this.state.house.name}</h1>
</Col>
</Row>
<Row>
<Col size="md-3" />
<Col size="md-6">
<img src={this.state.source} alt='image of house' />
</Col>
<Col size="md-3" />
</Row>
<Row>
<Col size="md-12">
<h4>{this.state.house.about}</h4>
</Col>
</Row>
</Col>
<Col size="md-3">
</Col>
</Row>
</Container>
)
}
但我希望您实际获得完整的网址而不是../client/src/images/house4.jpg
? :)