Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

javascript - 显示一些元素并保存其余元素以在之后显示(Showing a n number of elements and save the rest to show after)

I have my component that gets the products and insets an add every 20 products.

(我有我的组件来获取产品,并每20个产品插入一个添加项。)

I want to only show 21 elements from the array at a time (20 products and 1 add) while keeping the rest idle to load another 21 elements when the user scroll down to the bottom of the page.

(我只想一次仅显示数组中的21个元素(20个产品和1个添加项),而当用户向下滚动到页面底部时,保持其余部分空闲以加载另外21个元素。)

I have created a function _addToDisplay to loop and show only 21 products at a time and added a button for now to show 21 more.

(我创建了一个函数_addToDisplay来循环播放一次并仅显示21种产品,并且现在添加了一个按钮以显示21种产品。)

But I am getting this error: Line 161:25: Expected an assignment or function call and instead saw an expression no-unused-expressions.

(但是我遇到了这个错误:161:25行:期望一个赋值或函数调用,而是看到一个表达式no-unused-expressions。)

Referring to this line { displayedList.map(item => {

(引用此行{ displayedList.map(item => {)

I am really new to react and I am lost.

(我真的是新来的反应,我迷路了。)

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

const axios = require('axios');

class Products extends React.Component {
  // No need for a constructor
  // for just defining the state.
  // it would've been useful if we
  // wanted to use a prop value as
  // the initial state
  state = {
      displayedList : [],
      isLoading: false,
      error: null
    };

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

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

    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;
      });

      this.setState({ productsAndAdsList });
    }
  };

  _getProducts = () => {

    this.setState({ isLoading: true });
    // make the fetch call
    // also it would be easier if you
    // use axios (https://www.npmjs.com/package/axios)
    // for making http requests
    axios.get('http://localhost:3000/products').then(list => this._injectAdsInList(list.data))
      .catch(error => this.setState({ error, isLoading: false }));
  };

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

        this.setState({
            indexDisplayed  : this.state.indexDisplayed+21, 
            displayedList : displayedList
        });
    }


  _sortPrice = () => {
    const { productsAndAdsList } = this.state;
    // instead of mutating the origin array
    // create a new one, and update the state
    const sortedProducts = productsAndAdsList.sort((a, b) => a.price - b.price);
    this.setState({ productsAndAdsList: sortedProducts });
  };

  _sortSize = () => {
    const { productsAndAdsList } = this.state;
    // instead of mutating the origin array
    // create a new one, and update the state
    const sortedProducts = productsAndAdsList.sort((a, b) => a.size - b.size);
    this.setState({ productsAndAdsList: sortedProducts });
  };

  _sortId = () => {
    const { productsAndAdsList } = this.state;  
    const sortedProducts =  productsAndAdsList.sort((a, b) => {
  if (a.id < b.id)
    return -1;
  if (a.id > b.id)
    return 1;
  return 0;
});
    this.setState({ productsAndAdsList: 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() {
    // I personally prefer not to make any
    // http calls directly in componentDidMount
    // instead, creating a new function makes sense
    this._getProducts();
  }

  render() {

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

console.log(productsAndAdsList);
console.log(displayedList);
console.log(this._addToDisplay());
    // 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 => {
                        <div  key={item.id} 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>
                    })
                }

          <button onClick={this._addToDisplay()}>Load 21 MORE</button>

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

export default Products;
  ask by Natasha translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...