我得到了显示在我的react应用程序上的图像的路径,而不是实际图像,而在我的react-native应用程序上,这些图像根本不显示

如何解决我得到了显示在我的react应用程序上的图像的路径,而不是实际图像,而在我的react-native应用程序上,这些图像根本不显示

问题1:我创建了一个CRUD(CMS)应用程序,并在您创建文章的地方进行了反应。我的后端在node.js中,我的数据库在MySQL中。我也有一个本机应用程序,可以提取我在CMS上创建的所有文章。如何将添加到文章中的图像存储在哪里?在我后端的文件夹中?还是其他地方?

问题2:因此,我已经连接到数据库,并在CMS反应网页上显示标题,内容和图像。但是,当涉及到图像时,您只能看到路径即。 (C:\fakepath\Screenshot 2020-06-14 at 23.07.52.png),而不是实际图像。我不知道问题是否出在我的后端上,但是经过一些在线研究之后,很多人说,如果要显示实际图像而不是仅显示路径,则需要在src中添加require,有点像这样:

<img src={require('./logo.jpeg')} /> 

但是我做的方式却看不到如何使用img tag并添加src,因为我正在从后端获取image进行渲染,因此,不创建img标签。希望这有道理。

ViewAllArticles.js


class ViewAllArticles extends Component {
    state = {
        articles: []
      }

      getArticles = _ => {
        fetch('http://localhost:4000/articles')
        .then(response => response.json())
        .then(response => this.setState({ articles: response.data }))
          .catch(err => console.error(err))
        }

      componentDidMount() {
        this.getArticles();
      }

      renderArticle = ({ id,title,image }) => <div key={id}>{title},{image}</div>

  render() {
    const { articles } = this.state;
    return (
      <div>
        <h1>Home</h1>
        <div>
        {articles.map(this.renderArticle)}
        </div>
      </div>
    );
  }
}

export default ViewAllArticles;

如果没有require,您是否有其他想法知道为什么会这样? 我还为我的本地应用程序提取了相同的数据,但图像没有显示出来。

这是我的本机应用程序中的代码: largeTitle={item.title}可以正常工作并在卡片上显示所有标题,但是source={item.image}不能在同一张卡片上显示图像。

HomeFeed.js

import React,{ Component } from "react";
import { StyleSheet,Text,View,FlatList } from 'react-native';
import {AppleCard,AppOfTheDayCard} from 'react-native-apple-card-views';

export default class HomeFeed extends Component {
constructor() {
  super()
  this.state = {
    dataSource: []
  }
}

// https://github.com/WrathChaos/react-native-apple-card-views
renderItem = ({ item }) => {
  return (
    <View>
    <View style={styles.card}>
    <AppleCard
    largeTitle={item.title}
    footnoteText="subtitle placeholder"
    source={item.image}
    >
    </AppleCard>
      </View>
    </View>
  )
}

componentDidMount() {
  const url = 'http://localhost:4000/articles'
  fetch(url)
  .then((response) => response.json())
  .then((responseJson) => {
this.setState({
  dataSource: responseJson.data
})
  })
}

  render() {
return(
    <View style={styles.homeFeed}>
      <FlatList
        data={this.state.dataSource}
        renderItem={this.renderItem}
      />
      
    </View>
);
  }

}
const styles = StyleSheet.create({
  homeFeed: {
    flex: 1,backgroundColor: '#fff',alignItems: 'center',justifyContent: 'center'
  },card: {
    padding: 15
  }
  
});

这是我在node.js中的后端代码

index.js

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const { query } = require('express');

const multer = require('multer');
const upload = multer({dest: 'public/images'}); // uploaded article image here

const app = express();

//all queries go here
const SELECT_ALL_ARTICLES_QUERY = 'SELECT * FROM articles';


//create connection
const connection = mysql.createConnection({
    host: 'localhost',user: 'root',password: 'DidiLydiBibi96',database: 'myTherapy'
});

connection.connect(err => {
    if(err) {
        return err;
    }
});
//end of creating connection

app.use(cors());

app.get('/',(req,res) => {
    res.send('go to /articles to see articles')
});

//ROUTES

//Add new article
app.use('/image',express.static('public/images'));
app.get('/articles/add',upload.single('image'),res) => {

const { title,content,image } = req.query; //fields from db
const INSERT_ARTICLES_QUERY = `INSERT INTO articles (title,image) VALUES(?,?,?)`;
connection.query(INSERT_ARTICLES_QUERY,[title,image],(err,results) => {
    if(err) {
        return res.send(err)
    }
    else {
        return res.send('successfully added article')
    }
});
});

//View all articles
app.get('/articles',res) => {
    connection.query(SELECT_ALL_ARTICLES_QUERY,results) => {
        if(err) {
            return res.send(err)
        }
        else {
            return res.json({
                data: results
            })
        }
            });
});

app.listen(4000,() => {
    console.log('Articles server listening on port 4000')
});

解决方法

对于第一个问题,从服务器获取图像uri足够好,并且应由您的react应用程序处理将其转换为可见图像。 一种方法是更改​​您的renderArticles方法,例如:

Please input a string of text: we have at least one byte
full string was 'we have at least one byte'

1  we

2  have

3  at

4  least

5  one

6  byte

6 words at the end of the loop:

1  we
2  have
3  at
4  least
5  one
6  byte

);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-