【发布时间】:2024-01-20 22:52:01
【问题描述】:
我在 componentDidMount() 中调用的函数内设置状态,但我没有访问渲染中的状态值。
如何按时访问render方法内部的状态?
状态:
constructor() {
super();
this.state = {
check_for_amount: '',
};
}
componentdidmount():
componentDidMount() {
this.check_amount_left();
}
功能:
check_amount_left = () => {
const getSelected = this.props.navigation.state.params;
var ref = firebase.firestore().collection('discounts').where("rest_id", "==", getSelected.rest_id)
ref.onSnapshot((querySnapshot => {
var amount = querySnapshot.docs.map(doc => doc.data().amount);
this.setState({
check_for_amount: amount
});
}));
}
渲染:
render() {
return(
<View/>
<Text>
{this.state.check_for_amount}
</Text>
</View>
)
}
【问题讨论】:
-
您面临的具体问题是什么?
-
@AkshitMehra 就像我说的,我无法访问渲染方法中的状态。我正在该函数中设置状态,但无法在渲染中访问它
-
您确定
this.setState()确实在更新您的状态并且amount的值是您所期望的吗?哎呀,你自闭了<View/>。 -
你检查了函数中的数量值吗?您的第一个视图也有一个封闭标签,`
` 必须是 ` ` -
@AkshitMehra 为了简洁起见,我在里面使用了一个简单的视图和文本,请不要介意。
标签: reactjs react-native state render