【问题标题】:Randomize results onload React随机化结果 onload React
【发布时间】:2021-06-29 21:13:30
【问题描述】:

每次刷新页面时,我都会尝试随机化从 API 收到的结果。我有点卡在设置 onload 的方式上。

这是我的代码

  handleRandom = (e) => {
    this.getMarvelResponse(null, null, e);
  };
  componentDidMount() {
    const random = Math.floor(Math.random() * 1473);
    this.getMarvelResponse(null, null, this.state.offset);
    onload = () => {this.handleRandom(random)}
  }

  getMarvelResponse = (id, name, offset) => {
    getCharacters({
      id: id,
      name: name,
      offset: offset,
    }).then(({ characters }) => {
      this.setState(
        {
          characters: characters.filter(
            (chr) => !chr.thumbnail.path.match(imageFound)
          ),      

          selectedCard: null,
          offset: offset,
          name: name,
        },
        () => {
          console.log(this.state.characters);
        }
      );
    });

【问题讨论】:

    标签: reactjs random refresh onload


    【解决方案1】:

    您将不得不创建一个函数来随机播放它们。 https://stackoverflow.com/a/12646864/11765805我从这条评论中得到了这个

    function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    

    你会想在这里调用它

      getMarvelResponse = (id, name, offset) => {
        getCharacters({
          id: id,
          name: name,
          offset: offset,
        }).then(({ characters }) => {
    /////////Call Here
          this.setState(
            {
              characters: characters.filter(
                (chr) => !chr.thumbnail.path.match(imageFound)
              ),      
    
              selectedCard: null,
              offset: offset,
              name: name,
            },
            () => {
              console.log(this.state.characters);
            }
          );
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 2011-09-21
      • 1970-01-01
      • 2013-01-07
      相关资源
      最近更新 更多