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

时间:2019-04-19 17:18:46

标签: javascript reactjs react-native

在我的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));

1 个答案:

答案 0 :(得分:0)

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

这是guide,说明了如何使用它。

编辑1:

实际上,您可以将sectionlistflatlist那样用于要构建的复杂结构。

这是一个小例子:

>>>>Section_Code    UKPMS_Codes XSP_CLandCR Def_Values  Start_C End_C   Sect._Length    Survey_Date
> A3054010  LLRT    CL1     0   0   53  14/07/2011
> A3054010  LLRT    CL1 8.1 0   0   53  14/07/2011
> A3054010  LRRT    CL1     0   0   53  14/07/2011
> A3054010  LRRT    CL1 1.8 0   0   53  14/07/2011
> A3054010  LLTX    CL1     0   0   53  14/07/2011
> A3054010  LLTX    CL1 0.93    0   0   53  14/07/2011
> A3054010  LRTX    CL1     0   0   53  14/07/2011
> A3054010  LRTX    CL1 0.7 0   0   53  14/07/2011
> A3054010  LV3 CL1     0   0   53  14/07/2011
> A3054010  LV3 CL1 3.8 0   0   53  14/07/2011
> A3054010  LV10    CL1     0   0   53  14/07/2011

其中节列表中的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> ); } 字段可以是组件数组, 希望有帮助。