如何修复 React 中的"Element type is invalid: expected a string ... but got: object"错误



我正在使用 Node.js 后端在 React.js 前端工作,我正在尝试创建一个应用程序,允许用户上传图像,然后在用户主页上的图库中显示该图像。我遇到的问题是图库组件中的一个错误,上面写着"元素类型无效:预期字符串(用于内置组件(或类/函数(用于复合组件(但得到:对象",我似乎找不到它来自哪里,我也不真正理解它的含义。

我尝试注释掉不同的代码段,但错误保持不变。

前端库上的当前组件为:

import React, { Component } from 'react';
import axios from "axios";
import ReactGallery from 'react-photo-gallery';
import Lightbox from 'react-images';
import { loadAuthToken } from "../local-storage";
export default class Gallery extends Component {
constructor(props){
super(props);
this.state = {
images : [],
currentImage: 0,
lightboxIsOpen: false
};
}
componentDidMount() {
console.log("auth");
axios({
method: "GET",
url: "http://localhost:8080/api/images/",
headers: { authorization: `Bearer ${loadAuthToken()}` }
}).then(response => {
this.setState({
images: response.data
});
});
}
openLightbox(event, obj) {
this.setState({
currentImage: obj.index,
lightboxIsOpen: true,
});
}
closeLightbox() {
this.setState({
currentImage: 0,
lightboxIsOpen: false,
});
}
gotoPrevious() {
this.setState({
currentImage: this.state.currentImage - 1,
});
}
gotoNext() {
this.setState({
currentImage: this.state.currentImage + 1,
});
}
render() {
let photos = this.state.images.map(image => {
return {
src : '/api/images' + image.uri,
width : image.width,
height : image.height,
id :  image.id
}
});
if (!this.state.images.length) return null; 
return (
<div className="gallery">
{this.state.images.length ?
<ReactGallery
photos={photos}
onClick={this.openLightbox.bind(this)}
/>
:
<div className="no-images">
<h5 className="text-center">
You currently have no images in your photos gallery
</h5>
</div>
}
<Lightbox images={photos}
onClose={this.closeLightbox.bind(this)}
onClickPrev={this.gotoPrevious.bind(this)}
onClickNext={this.gotoNext.bind(this)}
currentImage={this.state.currentImage}
isOpen={this.state.lightboxIsOpen}/>
</div>
);
}
}

完整的前端在这里: https://github.com/beccaww/cats-client

后端在这里:https://github.com/beccaww/cats

我希望有一个用户上传的图像库,而不是错误消息。有没有人可以阐明错误及其可能意味着什么?

在第24行:您正在使用response.data,它为您提供了json对象,并且您已将图像状态设置为采用数组。 求解控制台.log(响应.数据(并检查所需的 JSON 对象值,然后更新图像状态。

axios({
method: "GET",
url: "http://localhost:8080/api/images/",
headers: { authorization: `Bearer ${loadAuthToken()}` }
}).then(response => {
console.log(response.data);
});

相关内容

最新更新