setState不会导致渲染React Native

时间:2018-01-14 09:04:31

标签: javascript http react-native

我一直在网上读到setState是异步的,这就是为什么当你使用setState()改变状态时它不会导致渲染,但我仍然不确定如何解决这个问题。 / p>

这是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>
      );
     }
  }

日志正确打印​​值。

有人可以帮忙吗。

1 个答案:

答案 0 :(得分:1)

问题是你将渲染中的部分重新定义为常量。直接使用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>
      );
    }
  }
相关问题