Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在页面上显示n个元素,其余元素保持空闲_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript 在页面上显示n个元素,其余元素保持空闲

Javascript 在页面上显示n个元素,其余元素保持空闲,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我正在创建一个react应用程序,我希望一次只显示21个元素,同时保持其余元素处于空闲状态。当用户滚动到页面底部时,显示另外21个元素,并重复此过程,直到所有元素都可见 我有一个函数\u injectAdsInList,它获取产品并每隔20个产品插入一个add,这是可行的,但我希望一次只显示21个元素(20个产品和1个add)当其余元素向下滚动时,保持空闲以加载另外21个元素时,我在屏幕上得到一个错误,在我的控制台中执行控制台日志时,我的数组displayedList返回为undefined 这

我正在创建一个react应用程序,我希望一次只显示21个元素,同时保持其余元素处于空闲状态。当用户滚动到页面底部时,显示另外21个元素,并重复此过程,直到所有元素都可见

我有一个函数
\u injectAdsInList
,它获取产品并每隔20个产品插入一个add,这是可行的,但我希望一次只显示21个元素(20个产品和1个add)当其余元素向下滚动时,保持空闲以加载另外21个元素时,我在屏幕上得到一个错误,在我的控制台中执行控制台日志时,我的数组
displayedList
返回为
undefined

这是我的组件

    import React from "react";
import { Loading } from "./LoadingComponent";

const axios = require('axios');

class Products extends React.Component {


  constructor(props){
        super(props);
        this.state = {
      displayedList : [],
      indexDisplayed : 0,
      isLoading: false,
      error: null
    }
    }



  _injectAdsInList = list => {
    // an array of your ads

    this.setState({ isLoading: false });
    const AdsList = ['111','2222'];

    let displayedList = this.state.displayedList;
    let indexDisplayed = this.state.displayedList;

    if (Array.isArray(list)) {
      const insertAdAt = 21;

      const productsAndAdsList = list.map((item, index) => {
        // not sure about this calculation
        // but this should be done here

        if (index % insertAdAt === 0 && index !== 0) {
          // its the 20th item insert an ad
          return AdsList[0];
        }

        // otherwise insert the item


        return item;



        });


        for(let i = indexDisplayed +1; i <= indexDisplayed + 21; i++ ){
         displayedList.push(productsAndAdsList[i]);
        }






      this.setState({productsAndAdsList});



    }
  };





  _getProducts = () => {

    this.setState({ isLoading: true });

    axios.get('http://localhost:3000/products').then(list => this._injectAdsInList(list.data))
      .catch(error => this.setState({ error, isLoading: false }));
  };

  _addToDisplay = ()=> {

    let displayedList = this.state.displayedList;
    let indexDisplayed = this.state.displayedList;
    let productsAndAdsList = this.state.displayedList;
        for(let i = indexDisplayed +1 ; i <= indexDisplayed + 21; i++ ){
            displayedList.push(productsAndAdsList[i]);
        }

        this.setState({
            indexDisplayed : this.state.indexDisplayed+21, displayedList : displayedList }, ()=>{console.log(this.state.displayedList)
        });
    }


  _sortPrice = () => {
    const { displayedList } = this.state;

    const sortedProducts = displayedList.sort((a, b) => a.price - b.price);
    this.setState({ displayedList: sortedProducts });
  };

  _sortSize = () => {
    const { displayedList } = this.state;

    const sortedProducts = displayedList.sort((a, b) => a.size - b.size);
    this.setState({ displayedList: sortedProducts });
  };

  _sortId = () => {
    const { displayedList } = this.state;  
    const sortedProducts =  displayedList.sort((a, b) => {
  if (a.id < b.id)
    return -1;
  if (a.id > b.id)
    return 1;
  return 0;
});
    this.setState({ displayedList: sortedProducts });
  }

   _timeAgo = (prevDate) => {
        const diff = Number(new Date()) - prevDate;
        const minute = 60 * 1000;
        const hour = minute * 60;
        const day = hour * 24;
        const month = day * 30;
        const year = day * 365;
        switch (true) {
            case diff < minute:
                const seconds = Math.round(diff / 1000);
                 return `${seconds} ${seconds > 1 ? 'seconds' : 'second'} ago`
            case diff < hour:
                return Math.round(diff / minute) + ' minutes ago';
            case diff < day:
                return Math.round(diff / hour) + ' hours ago';
            case diff < month:
                return Math.round(diff / day) + ' days ago';
            case diff < year:
                return Math.round(diff / month) + ' months ago';
            case diff > year:
                return Math.round(diff / year) + ' years ago';
            default:
                return "";
        }
    };

  componentDidMount() {

    this._getProducts();
  }

  render() {

    const { displayedList, isLoading, hasError } = this.state;

console.log(this.state.displayedList);

    // show spinner
    if (!hasError && isLoading) {
      return <Loading />;
    }

    // show error
    if (hasError && !isLoading) {
      return <p>error.message</p>;
    }

    return (
      <div>
       <div className="row">
            <div className="col-12">
                <button onClick={this._sortPrice}>sort by price lower to higher</button>
                <button onClick={this._sortSize}>sort by size small to big</button>
                <button onClick={this._sortId}>sort by Id</button>  
            </div>  
        </div>
        { displayedList.map(item => { return (
                        <div className="row">
              <div className="col-4">
                <p> Price: ${(item.price / 100).toFixed(2)}</p>
              </div>

              <div className="col-4">
                <p style={{ fontSize: `${item.size}px` }}> {item.face}</p>
              </div>
            <div className="col-3">
                  <p>Published: {this._timeAgo(new Date(item.date).getTime())}</p>
                </div>
            </div>
            ) } )

                }



       <div className="row">
            <div className="col-12">
                <p>END OF CATALOG</p>  
            </div>  
        </div>
      </div>
    );
  }
}

export default Products;
这是我数据库中的原始数据

 {
    "id": "29470-8qkpkhuqdct",
    "size": 15,
    "price": 999,
    "face": "( .-. )",
    "date": "Tue Nov 05 2019 20:29:01 GMT-0500 (Colombia Standard Time)"
  },
  {
    "id": "38405-fq66zcem9a5",
    "size": 27,
    "price": 787,
    "face": "( .o.)",
    "date": "Thu Nov 07 2019 13:32:17 GMT-0500 (Colombia Standard Time)"
  },
  {
    "id": "21765-r5f5rctbs6i",
    "size": 24,
    "price": 619,
    "face": "( `·´ )",
    "date": "Mon Nov 11 2019 20:57:19 GMT-0500 (Colombia Standard Time)"
  },
  {
    "id": "82780-5sypj693ojx",
    "size": 26,
    "price": 994,
    "face": "( ° ͜ ʖ °)",
    "date": "Fri Nov 15 2019 12:20:46 GMT-0500 (Colombia Standard Time)"
  },    
这是我在控制台日志中重复4次得到的结果

[] 0:{id:“71853-4k9d13grmxj”,尺寸:19,价格:4,正面:“.o.”,日期:2019年11月21日星期四11:06:00 GMT-0500(哥伦比亚标准时间)} 长度:1
proto:数组(0)

components/ProductsComponent.js:183,它指的是Price:${(item.Price/100).toFixed(2)}

在`\u injectAdsInList
末尾设置状态后,当您
console.log(this.state.displayedList)
得到什么。所以写
this.setState({productsAndAdsList,indexDisplayed:this.state.indexDisplayed+21,displayedList:displayedList},()=>{console.log(this.state.displayedList)})`好的,我复制并粘贴了你让我写的内容,我在控制台中重复了4次这个数组:[]0:undefined 1:{id:“71853-4k9d13grmxj”,大小:19,价格:4,面:“(.o.)”,日期:“2019年11月21日周四11:06:00GMT-0500(哥伦比亚标准时间)}长度:2 proto:array(0)你能把它添加到问题中吗?那个数组看起来很混乱。它应该看起来更像
[{id:“71853-4k9d13grmxj”,大小:19,价格:4,面:“(.o.)”,日期:“2019年11月21日星期四11:06:00 GMT-0500(哥伦比亚标准时间)”,{…},]
确定添加了我在控制台中得到的内容和原始阵列的一部分
 {
    "id": "29470-8qkpkhuqdct",
    "size": 15,
    "price": 999,
    "face": "( .-. )",
    "date": "Tue Nov 05 2019 20:29:01 GMT-0500 (Colombia Standard Time)"
  },
  {
    "id": "38405-fq66zcem9a5",
    "size": 27,
    "price": 787,
    "face": "( .o.)",
    "date": "Thu Nov 07 2019 13:32:17 GMT-0500 (Colombia Standard Time)"
  },
  {
    "id": "21765-r5f5rctbs6i",
    "size": 24,
    "price": 619,
    "face": "( `·´ )",
    "date": "Mon Nov 11 2019 20:57:19 GMT-0500 (Colombia Standard Time)"
  },
  {
    "id": "82780-5sypj693ojx",
    "size": 26,
    "price": 994,
    "face": "( ° ͜ ʖ °)",
    "date": "Fri Nov 15 2019 12:20:46 GMT-0500 (Colombia Standard Time)"
  },