首页 > 解决方案 > 项目更改时反应本机部分列表不重新渲染

问题描述

我的 react native 项目中有一个 sectionList。如果项目更改,它不会重新渲染。我的代码:

测试.js

class Test extends React.Component {
started = false;
causeData=[];
showLess=false;
items = [];

_start = () => {
    const { ws } = this.props;

    this.showLess = false;
    if (ws.causes.length) {
  this.causeData = {
    title: Language.causes,
    key: "cause",
    data: []
  };

  ws.causes.forEach(cause => {
    let causeDetails = {
      key: "cause_" + cause.id,
      name: "",
      value: cause.name,
      sortIndex: cause.sortIndex,
      progress: cause.progress
    };
    this.causeData.data.push(causeDetails);

    if (this.causeData.data.length > 4) {
      this.causeData.data = this.causeData.data.slice(0, 4);
    }
  });
  this.items.push(this.causeData);
  console.log("causeData", this.causeData);
  }  
  }
  }

 _renderItem = ({ item }) => {
     return (
          <View>
          <Text key={item.key} style={styles.text}>{`${item.name}  ${
            item.value
          }`}</Text>
        </View>
  );
 };

_renderSectionHeader = ({ section }) => {
   const { ws } = this.props;
   const showMore = ws.causes.length > 0 && !this.showLess;

  return (
    <View style={styles.sectionHeader}>
      <Text key={section.key} style={styles.header}>
        {section.title}
      </Text>
      {showMore && (
        <Button
          onPress={this._afterCauseAnswered}
          title={Language.showMore}
          data={this.items}
          accessibilityLabel={Language.causeDoneAccessibility}
        />
      )}
      </View>
    );
    };

   _keyExtractor = (item, index) => item.key;

  _afterCauseAnswered = () => {

    const { stepDone, ws } = this.props;
    this.causeData.data = { ...ws.causes };

    stepDone("showMoreAnswered");
    this.showLess = true;
  };

  render = () => {
  if (!this.started) {
  this.started = true;
  this._start();
  }
  return (
  <View style={styles.container}>
    <SectionList
      sections={this.items}
      extraData={this.items}
      renderItem={this._renderItem}
      renderSectionHeader={this._renderSectionHeader}
      keyExtractor={this._keyExtractor}
    />
  </View>
);
};
}

在我的部分列表部分标题中包含一个名为 showMore 的按钮。在初始渲染时它只会显示 5 个项目,而单击 showMore 它应该显示所有列表。这是我的功能。但是在单击 showMore 按钮时,它不会显示整个列表,仅显示 5 个项目,这意味着 sectionList 不会重新渲染。如何解决这个问题?我是新来的反应本地人。知道我错过了什么吗?任何帮助将不胜感激!

标签: reactjsreact-nativereact-native-sectionlist

解决方案


在使用新值按下 Button 调用后,保持itemsshowLess处于状态。setState它将重新渲染SectionList. 此外,如果您想通过显示的列表显示多个项目,则需要移动showLess到 item 元素,以便每个项目都知道如何显示它。


推荐阅读