【问题标题】:How to create infinite scroll in React and Redux?如何在 React 和 Redux 中创建无限滚动?
【发布时间】:2020-12-01 08:16:59
【问题描述】:
import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';

import {
    fetchRecipes
} from '../../store/actions';
import './BeerRecipes.css';

const BeerRecipes = ({recipesData, fetchRecipes}) => {

    const [page, setPage] = useState(1);
    const [recipes, setRecipes] = useState([]);
    const [loading, setLoading] = useState(true);


    useEffect(() => {
        fetchRecipes();
    }, [])

    return (

                <div className='beer_recipes_block'>
                    <div className='title_wrapper'>
                        <h2 className='title'>Beer recipes</h2>
                    </div>
                    <div className='beer_recipes'>
                        <ul className='beer_recipes_items'>
                            {
                                recipesData && recipesData.recipes && recipesData.recipes.map(recipe =>
                                    <li className='beer_recipes_item' id={recipe.id}>{recipe.name}</li>
                                )
                            }
                        </ul>
                    </div>
                </div>

    );
};

const mapStateToProps = state => {
    return {
        recipesData: state.recipes
    }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchRecipes: () => dispatch(fetchRecipes())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(BeerRecipes);

这是我想要创建无限滚动的组件,下面是我使用 axios 的 redux-action:

import axios from "axios";
import * as actionTypes from "./actionTypes";

export const fetchRecipesRequest = () => {
    return {
        type: actionTypes.FETCH_RECIPES_REQUEST
    }
}

export const fetchRecipesSuccess = recipes => {
    return {
        type: actionTypes.FETCH_RECIPES_SUCCESS,
        payload: recipes
    }
}

export const fetchRecipesFailure = error => {
    return {
        type: actionTypes.FETCH_RECIPES_FAILURE,
        payload: error
    }
}

export const fetchRecipes = (page) => {
   return (dispatch) => {
       dispatch(fetchRecipesRequest)
        axios
            .get('https://api.punkapi.com/v2/beers?page=1')
            .then(response => {
                const recipes = response.data;
                dispatch(fetchRecipesSuccess(recipes));
            })
            .catch(error => {
                const errorMsg = error.message;
                dispatch(fetchRecipesFailure(errorMsg));
            })
   }
}

我想创建一个卷轴。首先,我需要显示前 10 个元素,然后在每次加载时添加 5 个元素。我总共有 25 个元素,当列表完成后,它应该再次从前五个开始。

【问题讨论】:

    标签: reactjs redux axios


    【解决方案1】:

    假设您已经准备好加载下一页。您可能可以通过使用像 react-in-viewport 这样的包来简化整个过程,这样您就不必处理所有的滚动侦听器了。

    那你就这样用吧。

    import handleViewport from 'react-in-viewport';
     
    const Block = (props: { inViewport: boolean }) => {
      const { inViewport, forwardedRef } = props;
      const color = inViewport ? '#217ac0' : '#ff9800';
      const text = inViewport ? 'In viewport' : 'Not in viewport';
      return (
        <div className="viewport-block" ref={forwardedRef}>
          <h3>{ text }</h3>
          <div style={{ width: '400px', height: '300px', background: color }} />
        </div>
      );
    };
     
    const ViewportBlock = handleViewport(Block, /** options: {}, config: {} **/);
     
    const Component = (props) => (
      <div>
        <div style={{ height: '100vh' }}>
          <h2>Scroll down to make component in viewport</h2>
        </div>
        <ViewportBlock 
             onEnterViewport={() => console.log('This is the bottom of the content, lets dispatch to load more post ')} 
             onLeaveViewport={() => console.log('We can choose not to use this.')} />
      </div>
    ))
    

    这里发生的是,它会创建一个位于视口之外的“div”,一旦它进入视口(这意味着用户已经滚动到底部),您可以调用一个函数来加载更多帖子。

    注意:请记住为您的 fetch 函数添加某种限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多