我已安装此依赖项:
http://jfcaiceo.github.io/react-lightbox-component/
我正在尝试以动态方式进行渲染,但我无法成功。也许我做错了一步。
这是我的组成部分:
import React, { Component } from 'react'
import axios from 'axios'
import Lightbox from 'react-lightbox-component';
const URL = 'http://localhost:3001/houses';
class Casas extends Component {
constructor(props) {
super(props);
this.state = {
index: 0,
currentHouse: [],
photos: []
};
}
componentDidMount() {
axios.get(URL)
.then(res => {
this.setState({
currentHouse: res.data
})
})
}
render() {
const { currentHouse, index } = this.state;
const images = currentHouse.length && currentHouse[index] && currentHouse[index].photos;
const renderImages = images && images.map((photo, index) => {
return (
{
src: `../images/${photo}.jpg`
}
)
})
<div>
<div className="gallery">
<Lightbox images={renderImages} />
</div>
</div>
)
}
}
export default Casas
这是Axios提取的db.json。可能会渲染“照片”数组。
{
"houses": [
{
"id": 1,
"name": "some text",
"text": "some text",
"photos": [
"img_1",
"img_2",
"img_3"
]
},
{
"id": 2,
"name": "some text",
"text": "some text",
"photos": [
"img_1",
"img_2",
"img_3"
]
}
]
有人知道如何解决吗?
答案 0 :(得分:2)
希望始终采用以下格式的第三方插件react-lightbox-component
var images = {
[
{
src: 'some image url',
title: 'image title',
description: 'image description'
},
...
]
}
因此,在您的代码中,render()
currentHouse.length
为0,因此此行var images = houses.length && houses[index] && houses[index].photos;
中的图像将为0,然后renderImages也为0。
react-lightbox-component
收到0,因此不会渲染
然后您的应用抛出错误并停止。
要执行此操作,请执行以下操作:
currentHouse.length
的长度,然后渲染react-lightbox-component
如下所示:
{
this.state.currentHouse.length > 0
? <Lightbox images={renderImages }/>
: null
}
答案 1 :(得分:1)
您的代码中有一些语法错误。您必须从currentHouse.houses中获取图像,似乎您是直接从currentHouse中获取图像。下面的代码工作正常。请看看:
import React, {Component} from "react";
import axios from 'axios';
import Lightbox from 'react-lightbox-component';
class Casa extends Component {
constructor(props) {
super(props);
this.state = {
index: 0,
currentHouse: [],
photos: []
};
}
componentDidMount() {
axios.get('books.json')
.then(res => {
this.setState({
currentHouse: res.data
})
})
}
render() {
const {
currentHouse,
index
} = this.state;
const images = currentHouse.houses && currentHouse.houses.length && currentHouse.houses[index] && currentHouse.houses[index].photos;
const renderImages = images && images.map((photo, index) => {
return ({
src: `../images/${photo}.jpg`
})
});
return (
<div>
<div className = "gallery" > {images && <Lightbox images = {
renderImages}/> }</div>
</div>
)
}
}
export default Casa;