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

How to keep pictures after refreshing page on React?

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

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

讨论了这个问题(见下面的 link): 并且建议使用:

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

而不是:

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

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

错误:

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

为列表中的每一项添加唯一键。检查 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)

要解决此问题,您必须将 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} /> 

问题原因:

刷新页面后图像不可见,因为在主页上 link 是到 ./funnyanimal.gif 但在刷新页面后,您 link 到(例如第一张图片)是 ./one/funnyanimal.gif 不存在 - 这就是为什么所有图片都变得不可见的原因。

解决方法:

我把所有图片上的圆点都去掉了。标记并制作它们: <img src={"/funnyanimal.gif"} /> 而不是 <img src={"./funnyanimal.gif"} /> 这样 link 就成为了绝对路径,而不是路由的相对路径;因此,刷新页面后图像不会消失。