![](/img/trans.png)
[英]React - Element type is invalid: expected a string or a class/function but got: object
[英]How to fix “Element type is invalid: expected a string … but got: object” error in React
我正在用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對象,並且您已將圖像狀態設置為采用數組。 解決console.log(response.data)並檢查所需的json對象值,然后更新圖像狀態。
axios({
method: "GET",
url: "http://localhost:8080/api/images/",
headers: { authorization: `Bearer ${loadAuthToken()}` }
}).then(response => {
console.log(response.data);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.