javascript - setState 不会导致渲染 React Native

标签 javascript http react-native

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

这是我的部分列表:

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

关于javascript - setState 不会导致渲染 React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48248095/

相关文章:

javascript - 错误 : bundling failed: TypeError: Cannot read property 'bindings' of null

javascript - react native 导航 useTheme()

python - 如何从 HTTP 服务器下载图像 [Python/sockets]

php - 为什么 http_parse_headers 在我的 cli 脚本中未定义?

react-native - react 原生中的文本阴影

javascript - 绘制 Three.js BufferGeometry 线时,颜色不会粘在线段上

ios - 发送帖子请求 IOS 7

javascript - InDesign Server - 更新文本框架内容导致内容丢失或多余

javascript - 以更短的方式从数组中获取字符串

javascript - Braintree 插件,在处理时禁用提交按钮