问题
I have a FlatList that works as expected when using a plain old <Text>
tag, but when using a custom Component inside renderItem, the FlatList will not re-render when changing this.state.dayOfYear
. On app load, when I set this.state.dayOfYear
, it loads properly. But when I change state again, it will not change the 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;
回答1:
I'm pretty sure that your DayRow
items are being constructed before props.content
is being set, you need to grab the props when the component is mounting. Try adding this:
componentWillMount() {
const { content } = this.props;
this.setState({content: content});
}
EDIT
I missed the part about "re-rendering"...
Basically you need a block of code that updates your components state when its props change, react components have another function similar to componentWillMount
called componentWillReceiveProps
, try:
componentWillReceiveProps(nextProps) {
const { content } = nextProps;
this.setState({content: content});
}
回答2:
I had the same issue but resolved using extraData = {this.state}
Complete code is here
<FlatList
style={styles.listView}
data={this.state.readingArray}
extraData={this.state}
renderItem=
{({item})=>
来源:https://stackoverflow.com/questions/48312089/react-native-flatlist-not-re-rendering-with-custom-renderitem