【发布时间】:2018-08-05 10:36:21
【问题描述】:
我有这个 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>
)
};
};
【问题讨论】:
-
通过在构造函数之外设置像
this.state =这样的状态,您不会调用重新渲染。使用函数this.setState({ ... }),因为这将触发所需的生命周期运动 -
不要在构造函数之外分配给
state,而是使用setState -
另外,小建议:在像
etiqueta_id = this.props.etiqueta.id ;这样的行中,不要忘记前面的const(或let),否则你最终会创建一堆全局变量以后可能会出现问题。 -
@SterlingArcher 和 SrThompson 对此表示感谢,这是有道理的。我改变了,但一切看起来都一样。 (我会更新代码)
-
@kingdaro 谢谢,我来自 php,有时忘记做出正确的声明
标签: javascript reactjs react-native