Javascript React Native-为什么此状态对象在函数中为空?
我有一个React本地组件,它在一个列表中呈现一个图像库。因此,对于父列表中的每个项目,它都会被调用一次。 它接收两个道具,“etiqueta”具有项目的标题,“galleries”是一组库(javascript文本)。我知道它应该只接收我们需要渲染的库,但我不能这样做,所以现在,我正在发送所有库并在这个组件中过滤它们 问题:当我在ComponentDidMount中记录console.log状态时,一切看起来都很好,state.entries具有需要渲染的库。但当我试图在get Example2()中访问它时,它返回一个空数组。我不知道为什么会这样 此外,出于某种原因,get Example2()中的console.log在控制台中不断运行。为什么会这样 这是我正在尝试使用的图库: 谢谢你的时间当然,我希望我足够清楚,我是新的反应Javascript React Native-为什么此状态对象在函数中为空?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我有一个React本地组件,它在一个列表中呈现一个图像库。因此,对于父列表中的每个项目,它都会被调用一次。 它接收两个道具,“etiqueta”具有项目的标题,“galleries”是一组库(javascript文本)。我知道它应该只接收我们需要渲染的库,但我不能这样做,所以现在,我正在发送所有库并在这个组件中过滤它们 问题:当我在ComponentDidMount中记录console.log状态时,一切看起来都很好,state.entries具有需要渲染的库。但当我试图在get Example
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>
)
};
};
类EtiquetaDetail扩展组件{
建造师(道具){
超级(道具);
此.state={
滑块1活动滑块:0,
slider1Ref:null,
条目:[],
isMounted:错误
};
}
componentDidMount(){
让etiqueta_id=this.props.etiqueta.id;
如果(this.props.etiqueta){
//选择我们需要渲染的库
gallery=this.props.gallers.find(函数(obj){
返回obj.id_gal==etiqueta_id;
});
ENTRIES1=JSON.parse(gallery.data);
this.setState={
滑块1活动滑块:0,
slider1Ref:null,
参赛作品:ENTRIES1,
是的
};
console.log(this.state);//按预期输出所有内容
}
}
获取示例2(){
console.log(this.state.entries);//返回0
返回(
);
}
render(){
const etiqueta=this.props;
const{title}=this.props.etiqueta;
返回(
{title.rendered}
{this.example2}
)
};
};
当您需要在构造函数之外更新状态时,请使用this.setState
,让React知道它需要重新渲染
this.setState({
slider1ActiveSlide: 0,
slider1Ref: null,
entries: ENTRIES1,
isMounted: true
})
this.state=
的状态,您不会调用重新渲染。使用函数this.setState({…})
因为这将触发所需的生命周期运动,而不是在构造函数外部分配给state
,也可以使用setState
,小建议:在像这样的行上etiqueta\u id=this.props.etiqueta.id代码>不要忘记前面的常量(或let
),否则您将创建一组全局变量,这些变量可能会在以后引起问题。@SterlingArcher和SrThompson感谢您的帮助,这是有意义的。我变了,但一切看起来都一样。(我会更新代码)@kingdaro谢谢,我来自php,有时会忘记正确声明perfect!这就成功了!非常感谢你!example2()中的console.log一直在思考,这种行为正常吗?不太确定:/我建议使用普通函数而不是getter,为了简单起见,sakeI会尝试一下,我现在在他们的github中使用这个示例。再次感谢你@kilinkisget example()
将在您访问this.example2
时被调用,因此每当您的EtiquetaDetail
组件触发重新渲染时,它将被激发。看见