【问题标题】:React-Native: FlatList re-rendering every single itemReact-Native:FlatList 重新渲染每个项目
【发布时间】:2020-12-15 07:32:28
【问题描述】:

所以我有一个 FlatList,它可以接收一系列项目。当我滚动到底部时,我会将更多项目附加到该数组的末尾并显示给用户。

问题是当我们添加到我们的项目数组时,每个项目都会被渲染,有时甚至会渲染两次。

这里的代码被简化了。 /r/reactnative 无法回答这个问题。

constructor(props) {
super(props);
this.state = {itemsTest: ['A', 'A', 'A', 'A']}
}

render() {


// Key is fine, since none of my items are changing indexes. I am just adding new items.
return (

<FlatList

keyExtractor={(item,index) => index}

scroll

data={this.state.itemsTest}

renderItem={({item, index}) => <View style={{width: windowWidth}}><Text>{item}</Text></View>

onEndReached={() => this.nextItemsTest()}

onEndReachedThreshold={0.2}

</FlatList>
)
}







nextItemsTest() {

// From suggestions below, just add an element to this array.

console.log('nextItemsTest');

const x = ['A'];

// Have worked with many variations of setting state here. I don't think this is the issue.
this.setState((prevState) => ({itemsTest: [...prevState.itemsTest, ...x],}));}

这是输出。每次设置我的状态时,每个项目都会重新渲染(甚至两次)。

我只想重新渲染未更改的项目。谢谢。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您可以创建另一个纯组件,而不是直接在平面列表渲染中使用 View。所以它只会在其数据发生变化时重新渲染。例如,对于您的情况,它只重新渲染每个项目一次。

    解决办法

    第一次创建一个像这样的纯组件

    class SmartView extends PureComponent {
      render() {
        const {item, index} = this.props;
        return (
          <View style={{height: 300}}>
            {console.log('rendering', index)}
            <Text>{item}</Text>
          </View>
        );
      }
    }

    然后像这样在你的平面列表中用 SmartView 替换 View

     <FlatList
            keyExtractor={(item, index) => index.toString()}
            data={this.state.itemsTest}
            renderItem={({item, index}) => <SmartView item=                                
                                            {item} index={index} />}
            onEndReached={() => this.nextItemsTest()}
            onEndReachedThreshold={0.2}
          />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2016-12-06
      • 2018-12-16
      • 2020-03-17
      • 2021-12-29
      相关资源
      最近更新 更多