【问题标题】:How do I display/render image from mongoDB with reactjs?如何使用 reactjs 从 mongoDB 显示/渲染图像?
【发布时间】:2021-06-01 05:50:21
【问题描述】:

我想显示来自 MongoDB 的图像以做出反应。我已经使用 django 完成了后端工作以获取图像并将其保存在我的 ../assets/ 文件夹中,但是当我尝试使用它来获取它时显示为空白。 我需要将图像路径的端口从 localhost:3000 更改为 localhost:18000 默认情况下,react 使用 localhost:3000/img-path 来获取 img

【问题讨论】:

  • 所以将src 设置为'http://localhost:18000/assets/' + [image_name]
  • @Mosh Feu localhost:18000' + data.course_details.course_image_url} alt="课程图片" style={{ width: "100%" }} /> 但在检查代码和检查 src 时仍然使用 localhost:3000
  • 添加http:// - <img class="card-img-top text-center" src={'http://localhost:18000' + data.course_details.course_image_url} alt="Course image" style={{ width: "100%" }} />
  • @Mosh Feu 你能解释清楚吗。我不明白你的意思
  • 我可以试试 :) 在上面的评论中,您设置的网址以localhost:18000 开头可能会导致问题。相反,它应该以http:// 开头,然后是localhost:18000。是不是更清楚了?

标签: reactjs


【解决方案1】:

您可以使用setState() 存储图像并使用fetch() 调用API

import React, { Component } from 'react'

export default class Main extends Component {
    state = {
        data : []
    }
    componentDidMount(){

        fetch('http://localhost:18000/').then(res => res.json())
        .then(data=> this.setState({data}))

    }
    render() {

        console.log(this.state.data)

        return (
            <div>
                <h1>Main</h1>
                {this.state.data ? this.state.data.map(img => 
                (<div key={img._id}>{img ? <img src={require(`${img.img.path}`)} 
                alt={img.img.name}/>:<span>deleted</span>}</div>)): 
                <h3>loading</h3>}
            </div>
        )
    }
}

【讨论】:

  • 这里您没有讨论更改图像端口
猜你喜欢
  • 2022-12-14
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 2019-08-04
  • 2020-05-28
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
相关资源
最近更新 更多