获取随机生成的链接,使每个对象都不同

Get random generated links to be different for each of the object

我有一个这种形式的对象数组:

const myData = [
  {
    "image": "https://placedog.net/300?random",
    "name": "A",
  },
  {
    "image": "https://placedog.net/300?random",
    "name": "B",
  },
  {
    "image": "https://placedog.net/300?random",
    "name": "C",
  },
];

如您所见,图像是从随机生成的 link 访问的。问题是我为所有(在本例中为 3 个)对象获得了相同的图像。这是一种以某种方式“暂停”数据读取的方法,以便为每个对象显示不同的图像吗?

我将此对象置于状态,然后使用语义 UI 的网格在其上进行映射并在页面上显示对象:

import React, { Component } from 'react';
import { Grid, Image } from 'semantic-ui-react';
import './App.css';
import dogs from './data/dogs.json'; // put the data into a json file

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dogList: dogs,
    };
  }

  render() {
    const { dogList } = this.state;

    return (
      <div className='App'>
        <Grid>
          <Grid.Row>
            {dogList.map((dog) => (
              <Grid.Column className='grid-element'>
                <>
                  <div>{dog.name}</div>
                  <Image src={dog.image} />
                </>{' '}
              </Grid.Column>
            ))}
          </Grid.Row>
        </Grid>
      </div>
    );
  }
}

export default App;

您可以在每个 src 的末尾添加一个随机查询参数,以确保对每个图像进行后续网络请求,而不是使用浏览器的缓存。另一个例子:

重复:

<img src='https://placedog.net/300?random'>
<img src='https://placedog.net/300?random'>

不重复:

<img src='https://placedog.net/300?random&foo=bar'>
<img src='https://placedog.net/300?random&foo=barz'>

在您的代码中,使用:

<Image src={dog.image + '&foo=' + Math.random()} />

您的 'random' url 正在被浏览器缓存。您可以通过在查询字符串中附加一个唯一参数来解决此问题,例如缓存破坏者的“cb”。名称值对是任意的,但值应该是唯一的。将您的数据更改为如下内容:

const myData = [
  {
    "image": "https://placedog.net/300?randomc&cb=cachebust1",
    "name": "A",
  },
  {
    "image": "https://placedog.net/300?random&cb=cachebust2",
    "name": "B",
  },
  {
    "image": "https://placedog.net/300?random&cb=cachebust3",
    "name": "C",
  },
];