简体   繁体   中英

How to implement a 'load more' functionality in react with redux?

This is the current flow of displaying a listing in our page:

I am calling an action reducer ( getListing() ) to get a listing of items via mapDispatchToProps

class Listing extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pageSize: 10
        };

        this.props.getlisting(10);
    }

The parameter '10' is just determining how many items to show. So this returns a listing of 10 items which I then render in the Listing's render() method:

listings.map(listing => {
    return (
        <ListingCard
            key={listing.id}
            listing={listing}
        />
    );
})}

Quite straightforward until this point. However at the end of the list, I need to have a load more button to load the next 10 items of the list. I imagine the method to be:

handleLoadMore() {
    this.setState(prevState => ({    
        pageSize: prevState.pageSize + 10
    }));
    this.props.getListing(this.state.pageSize);
}

With the intention of now getting a listing of 20 instead of just 10. And so on and so forth (eg 30, 40, increments of 10).

However, this doesn't work because the entire listing will re-render upon triggering the handleLoadMore() . The usual 'load more' behavior keeps the initial result UI on the screen and just sort of appends the next X number of results.

How do I achieve this effect without re-rendering the entire list? Should I have a local state copy of the listings returned from the store?

Don't set anything in the local state. Simply make a call to this.props.getListing .

In your redux reducer/thunk/saga action, when it dispatches successfully, instead of replacing this.props.listings , add to it:

const initialState = {
  pageSize: 0,
  listings: []
}
​
function myApp(state, action) {
  if (typeof state === 'undefined') {
    return initialState
  }

  switch (action.type) {
     case FETCH_LISTINGS_SUCCESS:
          return {
            ..state,
            pageSize: state.pageSize + 10,
            listings: [...listings, ...action.listings]
          });
        default:
          return state
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM