我有一个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 回答
我非常确定你的
DayRow
项目是在props.content
被设置之前构建的,你需要在组件安装时 grab 道具 . 尝试添加此:EDIT 我错过了关于"re-rendering"的部分......基本上你需要一个代码块来更新你的组件状态,当它的道具改变时,反应组件有另一个类似于
componentWillMount
的函数叫componentWillReceiveProps
,试试:我有同样的问题,但使用extraData = 解决了
完整的代码在这里