我有这个React组件。运行正常。
import React, { Component } from 'react'
import Lightbox from 'react-lightbox-component';
const LightBoxTest = () => (
<div>
<Lightbox images={[
{
src: '../images/int_01.jpg'
},
{
src: '../images/int_02.jpg'
},
{
src: '../images/int_03.jpg'
}
]} />
</div>
);
export default LightBoxTest
但是我想通过使用Axios从json.db中获取数据以动态方式插入图像。我该怎么做?
这是我的json.db:
{
"interiors": [
{
"photos": [
"int_01",
"int_02",
"int_03"
}
]
}
我试图这样做,但是没有用:
import React, { Component } from 'react'
import axios from 'axios'
import Lightbox from 'react-lightbox-component';
const URL_INTERIORS = 'http://localhost:3001/interiors';
class LightBoxTest extends Component {
componentDidMount() {
axios.get(URL_INTERIORS)
.then(res => {
this.setState({
interiors: res.data[0],
interiorsPhotos: res.data[0].photos,
})
}
render() {
return (
<div>
<Lightbox images={[
this.state.interiorsPhotos.map((photo, index) => {
{
src: `../images/${photo}.jpg`
}
})
]} />
</div>
)
}
}
export default LightBoxTest
出现错误消息:
TypeError:无法读取null的属性“ interiorsPhotos”
答案 0 :(得分:2)
创建组件时,状态变量不存在。在类构造函数中声明它。
constructor (props) {
super(props)
this.state = {
interiors: null,
interiorsPhotos: [],
}
}