React-Native FlatList不使用自定义renderItem重新渲染 [英] React-Native FlatList not re-rendering with custom renderItem
问题描述
我有一个FlatList可以在使用普通的旧<Text>
标记时按预期工作,但是当在renderItem中使用自定义组件时,在更改this.state.dayOfYear
时FlatList将不会重新呈现.在应用程序加载时,当我设置this.state.dayOfYear
时,它会正确加载.但是,当我再次更改状态时,它不会更改FlatList.
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
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;
推荐答案
我很确定在设置props.content
之前已构建了DayRow
物品,在安装组件时需要抓住支柱. .尝试添加此内容:
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});
}
编辑
我错过了有关重新渲染"的部分.
基本上,您需要一个代码块,以在其属性更改时更新组件状态,使组件具有类似于componentWillMount
的另一个功能,称为componentWillReceiveProps
,请尝试:
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});
}
这篇关于React-Native FlatList不使用自定义renderItem重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!