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

时间:2018-01-18 00:23:03

标签: javascript reactjs listview react-native react-native-flatlist

我有一个FlatList在使用普通的旧<Text>标记时按预期工作,但在renderItem中使用自定义Component时,更改this.state.dayOfYear时FlatList不会重新呈现。在应用加载时,当我设置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;

2 个答案:

答案 0 :(得分:1)

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

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

修改 我错过了关于&#34;重新渲染的部分&#34; ... 基本上你需要一个代码块,当它的props改变时更新你的组件状态,反应组件有另一个类似于componentWillMount componentWillReceiveProps的函数,试试:

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

答案 1 :(得分:1)

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

完整代码在这里

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