簡體   English   中英

setState不會導致渲染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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM