[英]How not to infinite loop using setState in render REACT NATIVE
[英]setState not causing a render React Native
我一直在線閱讀setState是異步的,這就是為什么當您使用setState()
改變狀態時它不會導致渲染的原因,但是我仍然不確定如何解決此問題。
這是我的sectionList部分:
const sections = [ { data: [{ value: this.state.balance, editable: true }], title: 'balance'}, ];
然后,我進行API調用並設置this.state.balance,但余額未更新。
dismiss() { fetch(API) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson.balance); this.setState({ balance: responseJson.balance }); console.log("The balance is"); console.log(this.state.balance); }) .catch((error) => { console.error(error); }); }
render() { if (this.state.user) { const sections = [ { data: [{ value: 0 }], title: 'Completed challenges'}, { data: [{ value: this.state.balance, editable: true }], title: 'balance' }, ]; return ( <SectionList style={styles.container} renderItem={this._renderItem} renderSectionHeader={this._renderSectionHeader} stickySectionHeadersEnabled={true} keyExtractor={(item, index) => index} ListHeaderComponent={() => this._ListHeader()} sections={sections} /> ); } else { return ( <View style={styles.container}> <Button title="Sign in" onPress={() => {this.goToLogin()}}></Button> </View> ); } }
日志正確打印值。
有人可以幫忙嗎?
問題是您將渲染中的節重新定義為常量。 直接使用this.state。
render() {
if (this.state.user) {
return (
<SectionList
style={styles.container}
renderItem={this._renderItem}
renderSectionHeader={this._renderSectionHeader}
stickySectionHeadersEnabled={true}
keyExtractor={(item, index) => index}
ListHeaderComponent={() => this._ListHeader()}
sections={[
{ data: [{ value: 0 }], title: 'Completed challenges'},
{ data: [{ value: this.state.balance, editable: true }], title: 'balance' },
]}
/>
);
} else {
return (
<View style={styles.container}>
<Button title="Sign in" onPress={() => {this.goToLogin()}}></Button>
</View>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.