首页 文章

当道具改变时,React-native FlatList不会重新渲染行

提问于
浏览
16

我遇到了新的FlatList组件的问题 . 具体来说,它不会重新渲染它的行,即使该行依赖于变化的道具 .


FlatList文档说:

这是一个PureComponent,这意味着如果道具保持浅层相等,它将不会重新渲染 . 确保您的renderItem函数所依赖的所有内容在更新后作为非_ =的prop传递,否则您的UI可能无法更新更新 . 这包括数据支柱和父组件状态 .

THE QUESTION

但是,当我更改selectedCategory项目的ID时 - 应该指示行是否被“选中”的道具 - 我相信道具应该重新渲染 . 我错了吗?

我检查了列表和行组件的'componentWillReceiveProps'方法,列表接收更新就好了,但是从不调用行的生命周期方法 .

如果我在列表组件中包含一个随机的,无用的布尔状态值,并在道具更新时来回切换它,它可以工作 - 但我不知道为什么?

state = { updated: false };

componentWillReceiveProps(nextProps) {
  this.setState(oldstate => ({
    updated: !oldstate.updated,
  }));
}

<FlatList
  data={this.props.items.allAnimalCategories.edges}
  renderItem={this._renderRow}
  horizontal={true}
  keyExtractor={(item, index) => item.node.id}
  randomUpdateProp={this.state.updated}
/>

THE CODE

我的代码的结构是这样的:我有一个包含所有逻辑和状态的容器组件,它包含一个FlatList组件(表示,无状态),它还包含一个自定义的表示行 .

Container
  Custom list component that includes the FlatList component
  (presentational, stateless) and the renderRow method
    Custom row (presentational, stateless)

容器包含此组件:

<CustomList
   items={this.props.viewer}
   onCategoryChosen={this._onCategoryChosen}
   selectedCategory={this.state.report.selectedCategory}
 />

CustomList:

class CustomList extends Component {
  _renderRow = ({ item }) => {
    return (
      <CustomListRow
        item={item.node}
        selectedCategory={this.props.selectedCategory}
        onPressItem={this.props.onCategoryChosen}
      />
    );
  };

  render() {
    return (
      <View style={_styles.container}>
        <FlatList
          data={this.props.items.categories.edges}
          renderItem={this._renderRow}
          horizontal={true}
          keyExtractor={(item, index) => item.node.id}
          randomUpdateProp={this.state.updated}
        />
      </View>
    );
  }

}

(数据来自Relay)

最后一行:

render() {
    const idsMatch = this.props.selectedCategory.id == this.props.item.id;
    return (
      <TouchableHighlight onPress={this._onItemPressed}>
        <View style={_styles.root}>
          <View style={[
              _styles.container,
              { backgroundColor: this._getBackgroundColor() },
            ]}>
            {idsMatch &&
              <Image
                style={_styles.icon}
                source={require('./../../res/img/asd.png')}
              />}
            {!idsMatch &&
              <Image
                style={_styles.icon}
                source={require('./../../res/img/dsa.png')}
              />}
            <Text style={_styles.text}>
              {capitalizeFirstLetter(this.props.item.name)}
            </Text>
          </View>
          <View style={_styles.bottomView}>
            <View style={_styles.greyLine} />
          </View>
        </View>
      </TouchableHighlight>
    );
  }

这行不是那么有趣,但我把它包括在内,表明它完全是无国籍的,并且依赖于它的父母道具 .

状态更新如下:

_onCategoryChosen = category => {
    var oldReportCopy = this.state.report;
    oldReportCopy.selectedCategory = category;
    this.setState(Object.assign({}, this.state, { report: oldReportCopy }));
  };

州看起来像这样:

state = {
    ...
    report: defaultStateReport,
  };

const defaultStateReport = {
  selectedCategory: {
    id: 'some-long-od',
    name: '',
  },
  ...
};

2 回答

  • 40

    这里的问题在于:

    • 您正在改变现有的状态片而不是创建变异副本

    _onCategoryChosen = category => {
        var oldReportCopy = this.state.report; // This does not create a copy!
        oldReportCopy.selectedCategory = category;
        this.setState(Object.assign({}, this.state, { report: oldReportCopy }));
    };
    

    这应该是

    _onCategoryChosen = category => {
        var oldReportCopy = Object.assign({}, this.state.report);
        oldReportCopy.selectedCategory = category;
        // setState handles partial updates just fine, no need to create a copy
        this.setState({ report: oldReportCopy });
    };
    

    • FlatList的道具保持不变,你的 _renderRow 函数可能依赖于确实改变的 selectedCategory prop(如果不是第一个错误),但FlatList组件不知道这一点 . 要解决此问题,请使用extraData prop .
    <FlatList
      data={this.props.items.categories.edges}
      renderItem={this._renderRow}
      horizontal={true}
      keyExtractor={(item, index) => item.node.id}
      extraData={this.props.selectedCategory}
    />
    
  • 9

    你可以解决这个问题,将 props 传递给 flat list 这样的 flat list

    <FlatList
        data={this.props.data}
        extraData={this.props}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem}
      />
    

相关问题