我有这个 React-Native 组件,它在列表中呈现一个图像库。因此,该父列表中的每个项目都会调用一次。 它接收两个 props,“etiqueta”(具有项目的标题)和“gallery”(画廊数组(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>
)
};
};
最佳答案
当您需要在构造函数之外更新状态时,请使用 this.setState
,让 React 知道它需要重新渲染。
this.setState({
slider1ActiveSlide: 0,
slider1Ref: null,
entries: ENTRIES1,
isMounted: true
})
关于javascript - React Native - 为什么这个状态对象在函数中是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980583/