在React页面刷新后如何保存图片?

时间:2019-01-14 06:29:39

标签: javascript reactjs redux react-dom

使应用程序正常运行,但刷新页面后,图像变得不可见...

演示:https://demo-old.herokuapp.com

讨论了该问题(请参见下面的链接):React won't load local images,建议使用:

<img src={require('./funnyanimal.gif')} /> 

代替:

<img src={"./funnyanimal.gif"} />

但是它没有编译并产生如下错误:

错误:

./src/App.js
Module not found: Can't resolve './funnyanimal.gif' in '/app/src'

3 个答案:

答案 0 :(得分:0)

要解决此问题,您必须将file-loader添加到您的Webpack配置中。

安装:

首先,运行以下命令以安装软件包:

npm i -D file-loader

然后,将此配置添加到您的webpack.config.js文件中:

module.exports = {
  ...
  module: {
    ...
    rules: [
      ...
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {},
          },
        ],
      },
    ],
  },
};

用法:

import image from './picture.png';

...

<img src={image} /> 

答案 1 :(得分:0)

问题原因:

刷新页面后图像不可见,因为在主页上的链接是指向./funnyanimal.gif的,但是刷新路径上的页面后,您可以链接到(例如,链接到第一张图像) )是./one/funnyanimal.gif,它不存在-为什么所有图像都不可见。

解决方案:

我从所有img中删除了该点。标记并制作它们:<img src={"/funnyanimal.gif"} />代替<img src={"./funnyanimal.gif"} />这样,链接是指向绝对路径而不是相对于路径的链接;因此,刷新页面后图像不会消失。

答案 2 :(得分:-1)

为列表中的每个项目添加唯一键。检查Web控制台检查器,然后修复这些错误。

此处更多信息https://reactjs.org/docs/lists-and-keys.html#keys

index.js:1452 Warning: Each child in an array or iterator should have a unique "key" prop.

    in ul (at Six.js:15)
    in Six (created by Route)
    in Route (at App.js:113)
    in div (at App.js:112)
    in div (at App.js:95)
    in div (at App.js:28)
    in div (at App.js:19)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:18)
    in AppRouter (at src/index.js:7)