我有一个React-Native组件,它在列表中呈现图像库。因此,对于该父列表中的每个项目,它都会被调用一次。 它接收两个道具,“etiqueta”,其具有项目的标题,以及“画廊”,它是一系列的画廊(javascript文字)。我知道它应该只接收我们需要渲染的图库,但是我不能这样做,所以现在,我发送所有的图库并在这个组件中过滤它们。
问题:当我在console.log中时,ComponentDidMount中的状态一切都很好,state.entries有需要渲染的库。但是当我尝试在 get Example2()中访问它时,它返回一个空数组。我不确定为什么会这样。
而且,由于某种原因, get Example2()中的console.log在控制台中一次又一次地运行。为什么会这样?
这是我正在尝试使用的图库:https://github.com/archriss/react-native-snap-carousel
感谢您的时间,我希望我很清楚,我是React的新手。
class EtiquetaDetail extends Component {
constructor(props) {
super(props);
this.state = {
slider1ActiveSlide: 0,
slider1Ref: null,
entries: [],
isMounted: false
};
}
componentDidMount() {
let etiqueta_id = this.props.etiqueta.id ;
if ( this.props.etiqueta ) {
// select the gallery we need to render
gallery = this.props.galleries.find(function (obj) {
return obj.id_gal === etiqueta_id;
});
ENTRIES1 = JSON.parse( gallery.data );
this.setState = {
slider1ActiveSlide: 0,
slider1Ref: null,
entries: ENTRIES1,
isMounted: true
};
console.log(this.state); // this outputs everything as expected
}
}
get example2 () {
console.log(this.state.entries); // returns 0
return (
<View>
<Carousel
data={ this.state.entries }
/>
</View>
);
}
render() {
const etiqueta = this.props;
const { title } = this.props.etiqueta;
return (
<Card>
<CardSection>
<View>
<Text>{title.rendered}</Text>
</View>
</CardSection>
<SafeAreaView>
<View}>
<ScrollView>
{ this.example2 }
</ScrollView>
</View>
</SafeAreaView>
</Card>
)
};
};
答案 0 :(得分:1)
当你需要更新构造函数之外的状态时,使用this.setState
,让React知道它需要重新渲染。
this.setState({
slider1ActiveSlide: 0,
slider1Ref: null,
entries: ENTRIES1,
isMounted: true
})