【问题标题】:dispay image and video from database with react js使用 React js 显示数据库中的图像和视频
【发布时间】:2020-08-20 22:59:57
【问题描述】:

嘿,伙计们,我正在尝试使用 react 从数据库中显示我的视频和图像,但是每当我使用 require(../../uploads/${this.state.classDt.filename}) 时出现此错误,其中文件名是我组件中的一个状态,但如果我直接从我的上传它显示的文件夹,如果我 console.log(this.state.classDt.filename) 它可以工作。如果我不使用 require() 它不会显示错误但不会显示图像或视频..请帮助。

我的代码

import React from 'react'
import ClassWall from './ClassWall'

class ClassSession extends React.Component{
    constructor(){
        super()
        this.state = {
            classDt: [],
            schoolDt:[],
            classtitle:[],
            classDate:[],
        }
    }
    componentDidMount(){
        this.getClassData()
        
    }
    getClassData = async()=>{
        try {
            const response = await fetch(`http://localhost:4000/ClassWalls/media/${this.props.match.params.id}`)
            const Parse = await response.json()
                if(Parse === "can't find class"){
                    console.log('cant find class')
                }else{
                    
                    this.setState({schoolDt:Parse.fileDT.school})
                    this.setState({classtitle:Parse.fileDT.title})
                    this.setState({classDate:Parse.fileDT.date})
                    this.setState({classDt:Parse})
                }
        
        } catch (error) {
            console.log(error.message) 
        }
    }

    render(){
       
        return(
            <div>
                <p>{
                    this.state.classDt.filename
                }</p>
                <video id="1" alt="pic" data-src{require(`../../uploads/${this.state.classDt.filename}`)}></video>

使用 require 时出错

×
Error: Cannot find module './undefined'

【问题讨论】:

  • 是公共目录下的上传文件夹,即公开访问?
  • http://localhost:4000/ClassWalls/media/${this.props.match.params.id} api 的响应是什么?

标签: javascript node.js reactjs


【解决方案1】:
<video id="1" alt="pic" 
data-src={(this.state.classDt && this.state.classDt.filename) ? require(`../../uploads/${this.state.classDt.filename}` : '')}
></video>

只有在 this.state.classDt.filename 存在时才需要它。

【讨论】:

  • @princerandy 欢迎您 :) 如果有帮助,请选择它作为答案 ;)
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
相关资源
最近更新 更多