如何在React中提高递归组件的性能?

问题描述 投票:0回答:1

在我的React Native Expo项目中,我创建了一个自我调用的递归注释组件,以呈现嵌套的注释线程。

但是,一旦评论的数量变得太大,性能开始降低,它不是非常用户友好。我已经尝试改变api如何调用检索该评论和其他一些小调整的结构,但无济于事。

我想我需要以某种方式使用shouldComponentUpdate,只在某些状态发生变化时才重新渲染,主要是注释是打开还是折叠。

有没有办法提高React中递归组件的性能?

import { FontAwesome } from "@expo/vector-icons";
import dateFns from "date-fns";
import { inject } from "mobx-react";
import PropTypes from "prop-types";
import React from "react";
import {
  ActivityIndicator,
  StyleSheet,
  TouchableHighlight,
  View
} from "react-native";
import Collapsible from "react-native-collapsible";
import HTMLView from "react-native-htmlview";
import { Text, withTheme } from "react-native-paper";
import ApiService from "../services/ApiService";

class Comment extends React.Component {
  static propTypes = {
    api: PropTypes.instanceOf(ApiService).isRequired,
    commentIds: PropTypes.arrayOf(PropTypes.number).isRequired
  };

  state = {
    comments: null
  };

  componentDidMount() {
    this.fetchStoryComments();
  }

  async fetchStoryComments() {
    const { api, commentIds } = this.props;
    try {
      let comments = await api.fetchStoryComments(commentIds);
      comments = comments.map(comment => {
        const commentCopy = comment;
        commentCopy.isCollapsed = false;
        return commentCopy;
      });
      this.setState({
        comments
      });
    } catch (error) {
      // HANDLE ERROR
    }
  }

  toggleCollapse(commentId) {
    this.setState(prevState => ({
      comments: prevState.comments.map(comment =>
        comment.id === commentId
          ? Object.assign(comment, { isCollapsed: !comment.isCollapsed })
          : comment
      )
    }));
  }

  render() {
    const { comments } = this.state;
    const { api } = this.props;

    return comments ? (
      comments.map(
        comment =>
          comment && (
            <View key={comment.id} style={styles.commentContainer}>
              <TouchableHighlight
                onPress={() => this.toggleCollapse(comment.id)}
              >
                <View style={styles.commentHeader}>
                  <Text style={styles.commentHeaderText}>
                    {`${comment.by} ${dateFns.distanceInWordsToNow(
                      new Date(comment.time * 1000)
                    )} ago`}
                  </Text>
                  <Text style={styles.commentHeaderText}>
                    {comment.isCollapsed ? (
                      <FontAwesome name="plus" />
                    ) : (
                      <FontAwesome name="minus" />
                    )}
                  </Text>
                </View>
              </TouchableHighlight>
              <Collapsible duration={200} collapsed={comment.isCollapsed}>
                <View style={styles.comment}>
                  <HTMLView
                    addLineBreaks={false}
                    stylesheet={htmlStyles}
                    textComponentProps={{ style: styles.commentText }}
                    value={comment.text}
                  />
                  {"kids" in comment && (
                    <View style={styles.kids}>
                      <Comment api={api} commentIds={comment.kids} />
                    </View>
                  )}
                </View>
              </Collapsible>
            </View>
          )
      )
    ) : (
      <ActivityIndicator
        style={styles.activityIndicator}
        size="small"
        color="#fff"
      />
    );
  }
}

export default inject("api")(withTheme(Comment));
javascript reactjs react-native
1个回答
0
投票

你尝试过使用flatlist而不是映射一堆视图吗?

这是一个guide解释如何使用它。

编辑1:

你可以使用像sectionlist这样的flatlist,用于复杂的结构,就像你正在建造的那样。

这是一个小例子:

render() {
    const a = ['comment 1 a', 'comment 2 a', 'comment 3 a'];
    const b = ['comment 1 b', 'comment 2 b'];
    const c = ['comment 1 c'];

    return (
      <View style={{ marginTop : (Platform.OS) == 'ios' ? 20 : 0 }}>
        <SectionList
          sections={[
            { comment: 'Comment a with subcomponents a', data: a },
            { comment: 'Comment b with subcomponents b', data: b },
            { comment: 'Comment c with subcomponents c', data: c },
          ]}
          renderSectionHeader={ ({section}) => <Text> { section.comment } </Text> }
          renderItem={ ({item}) => <Text> { item } </Text> }
          keyExtractor={ (item, index) => index }
        />
      </View> 
    );
  }

部分列表中的data字段可能是一个组件数组,希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.