如何创build“加载更多”function,而不需要在React / Node中重新渲染整个组件?

我试图创build一个简单的民意调查程序,在那里你可以进行新的民意调查。

在“MyPolls”一节中,我希望它只呈现我所做的前5轮投票,而不是呈现整个投票列表。

在底部是一个“加载更多”button,在点击后,再加载5个民意调查等等。

我一直在使用Mongoose / MongoDB后端,我的方法是使用skiplimit

我已经设法实现这个function,但问题是整个组件重新呈现,这是一个用户烦恼,因为你必须再次向下滚动点击“加载更多”button。

这是我的应用程序: https : //voting-app-drhectapus.herokuapp.com/

(使用这些login信息是否方便:用户名: riverfish@gmail.com密码: 123

然后转到My Polls页面。

MyPoll.js

 import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../actions'; class MyPolls extends Component { constructor(props) { super(props); this.state = { skip: 0 }; } componentDidMount() { this.props.fetchMyPolls(this.state.skip); this.setState({ skip: this.state.skip + 5 }); } sumVotes(polls) { return polls.reduce((a, b) => { return a.votes + b.votes; }); } loadMore(skip) { this.props.fetchMyPolls(skip); const nextSkip = this.state.skip + 5; this.setState({ skip: nextSkip }); } renderPolls() { return this.props.polls.map(poll => { return ( <div className='card' key={poll._id}> <div className='card-content'> <span className='card-title'>{poll.title}</span> <p>Votes: {this.sumVotes(poll.options)}</p> </div> </div> ) }) } render() { console.log('polls', this.props.polls); console.log('skip:', this.state.skip); return ( <div> <h2>My Polls</h2> {this.renderPolls()} <a href='#' onClick={() => this.loadMore(this.state.skip)}>Load More</a> </div> ); } } function mapStateToProps({ polls }) { return { polls } } export default connect(mapStateToProps, actions)(MyPolls); 

动作创造者:

 export const fetchMyPolls = (skip) => async dispatch => { const res = await axios.get(`/api/mypolls/${skip}`); dispatch({ type: FETCH_MY_POLLS, payload: res.data }); } 

民意调查路线:

 app.get('/api/mypolls/:skip', requireLogin, (req, res) => { console.log(req.params.skip); Poll.find({ _user: req.user.id }) .sort({ dateCreated: -1 }) .skip(parseInt(req.params.skip)) .limit(5) .then(polls => { res.send(polls); }); }); 

整个github回购: https : //github.com/drhectapus/voting-app

我明白,可能实施此function的方法可能是最好的解决scheme,所以我打开任何build议。

看起来像重新渲染是由点击“加载更多”链接实际上导致反应路由器导航到一个新的路由,导致整个MyPolls组件重新呈现的事实触发。

只需用<button onClick={...}>replace<a href='#' onClick={...}>

如果你不想使用button ,你也可以改变onClick函数

 const onLoadMoreClick = e => { e.preventDefault(); // this prevents the navigation normally occuring with an <a> element this.loadMore(this.state.skip); }