React-Native FlatList 不使用自定义 renderItem 重新渲染

React-Native FlatList not re-rendering with custom renderItem

我有一个 FlatList,在使用普通的旧 <Text> 标记时可以按预期工作,但是在 renderItem 中使用自定义组件时,FlatList 在更改 this.state.dayOfYear 时不会重新呈现。在应用加载时,当我设置 this.state.dayOfYear 时,它会正确加载。但是当我再次改变状态时,它不会改变 FlatList。

FlatList 代码

<FlatList
    style={{flex: 1}}
    extraData={this.state}
    data={reading_data[this.state.dayOfYear]}
    renderItem={({item}) => <DayRow content={item}/>} //does not work
    // renderItem={({item}) => <Text>{item.ref}</Text>} //Works perfectly
    keyExtractor={(item, index) => index}
/>

自定义 renderItem (DayView.js)

import {StyleSheet, Text, View} from 'react-native'
import React, {Component} from 'react';

export default class DayRow extends React.Component {

    constructor(props) {
        super(props)
        console.log(props)
        this.state = {
            content: props.content,
        }
    }

    render() {
        return (
            <View style={styles.row}>
                <Text style={styles.text}>{this.state.content.ref}</Text>
                <View style={{height: 2, backgroundColor:'#abb0ab'}}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    row: {
        backgroundColor: '#fff'
    },
    text: {
        fontSize: 16,
        padding: 10,
        fontWeight: 'bold',
        color: '#000',
    },
});

module.exports = DayRow;

我很确定你的DayRow项目是在props.content设置之前构建的,你需要在安装组件时抓住道具。尝试添加:

componentWillMount() {
  const { content } = this.props;
  this.setState({content: content});
}

编辑 我错过了关于 "re-rendering" 的部分...... 基本上你需要一个代码块来更新你的组件状态当它的道具改变时,反应组件有另一个类似于 componentWillMount 的函数叫做 componentWillReceiveProps,试试:

componentWillReceiveProps(nextProps) {
  const { content } = nextProps;
  this.setState({content: content});
}

我遇到了同样的问题,但使用 extraData = {this.state}

解决了

完整代码在这里

<FlatList
  style={styles.listView}
  data={this.state.readingArray}
  extraData={this.state}
  renderItem=
  {({item})=>