如何在React/Node中创建“加载更多”特性而不重新渲染整个组件?

3
我正在尝试创建一个简单的投票应用程序,您可以在其中创建新投票。
在“我的投票”部分,我希望仅呈现我制作的前5个投票,而不是呈现整个投票列表。
底部有一个“加载更多”按钮,点击后会加载另外5个投票,以此类推。
我一直在使用Mongoose/MongoDB后端,我的方法是使用skiplimit
我已经成功实现了这个功能,但问题是整个组件重新渲染,这对用户来说很烦人,因为您必须再次向下滚动才能单击“加载更多”按钮。
这是我的应用程序:https://voting-app-drhectapus.herokuapp.com/ (为方便起见,您可以使用以下登录详细信息: 用户名: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 我知道我的实现方法可能不是最好的解决方案,因此我愿意听取任何建议。

当您在loadMore方法中更新状态时,MyPolls组件会重新渲染,这是期望的行为,因为它会显示更多的投票。不期望的是因为URL的更改而发生的向上滚动。@forrert的答案是正确的 :) - mario199
1个回答

3

看起来重新渲染是由于点击“加载更多”链接实际上导致React Router导航到新路由,从而导致整个MyPolls组件重新渲染。

只需用<button onClick={...}>替换<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);
}

这是一个好答案。我在 https://codesandbox.io/s/mjz434j518 上测试过了。我重新创建了一个类似但简化的用例,并首先尝试了没有 preventDefault() 的情况,它在 herokuapp 上像你的情况一样工作。然后我添加了 preventDefault(),现在它完美地工作 :) - mario199

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接