【问题标题】:How to retrieve fetch data in my native app如何在我的本机应用程序中检索获取数据
【发布时间】:2018-10-02 18:16:48
【问题描述】:

我想知道如何在我的应用中查看我的 fetch 查询中的数据。

我有一个从 React native 获取的节点,我想显示响应。

节点部分;

app.get('/balance', function(req, res){
    //calling the function
    res.jsonp('0');
      console.log("CRYPTO CALLED");
      });

反应函数;

_getBalanceFromApiAsync() {
 fetch('http://192.168.1.100:3000/ballance')
    .then(response => response.json())
    .then(responseJson => {
      console.log(responseJson);

      return responseJson;
    })
    .catch((error) => {
      console.error(error);
    });
}

我可以在节点控制台和反应控制台中看到结果。但它不起作用的地方就在这里。

原生应用;

<Text style={styles.getStartedText}>Your Wallet Balance</Text>
          <Text> {this._getBalanceFromApiAsync()}</Text>
           </View>

函数正在执行,但我想显示返回值,因为它是文本字段保持为空

谢谢

【问题讨论】:

  • 您要显示哪些具体数据?您的函数似乎将一个对象返回到要显示的文本字段中。对象不能在反应原生文本标签中显示。
  • 我试图在这种情况下显示一个整数 0
  • 我正在尝试,所以不确定我是否做得对。尝试返回一个对象 {ballance:0} 并引用 responseJson.ballance 但我得到相同的结果
  • 在你的函数中只返回 responseJson.ballance ?

标签: react-native


【解决方案1】:

很简单,你需要 setState 来重新渲染组件。尝试这样做

constructor(props){
   super(props)
this.state = {
    textData: ''
}
}

componentDidMount(){
this.getBalanceFromApiAsync()
}

getBalanceFromApiAsync() {
 fetch('http://192.168.1.100:3000/ballance')
    .then(response => response.json())
    .then(responseJson => {
      console.log(responseJson);
       this.setState({
      textData: responseJson
})
    })
    .catch((error) => {
      console.error(error);
    });
}

<Text style={styles.getStartedText}>Your Wallet Balance</Text>
          <Text> {this.state.textData}</Text>
           </View>

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2011-07-02
    • 2016-11-01
    • 1970-01-01
    相关资源
    最近更新 更多