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

IT技术 javascript reactjs listview react-native react-native-flatlist
2021-05-11 03:45:12

我有一个 FlatList 在使用普通旧<Text>标签时可以按预期工作,但是在 renderItem 中使用自定义组件时,FlatList 在更改this.state.dayOfYear. 在应用程序加载时,当我设置时this.state.dayOfYear,它会正确加载。但是当我再次更改状态时,它不会更改 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}
/>

自定义渲染项(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;
2个回答

我很确定您的DayRow物品props.content在设置之前已经构建好了,您需要在安装组件时抓住props。尝试添加这个:

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

编辑 我错过了关于“重新渲染”的部分......基本上你需要一个代码块来在它的props改变时更新你的组件状态,react组件有另一个类似于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})=>