首页 文章

React-Native FlatList不使用自定义renderItem重新呈现

提问于
浏览
1

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

FlatList Code

<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}
/>

Custom 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;

2 回答

  • 1

    我非常确定你的 DayRow 项目是在 props.content 被设置之前构建的,你需要在组件安装时 grab 道具 . 尝试添加此:

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

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

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

    我有同样的问题,但使用extraData = 解决了

    完整的代码在这里

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

相关问题