首页 > 解决方案 > 使用本机反应的 GET 请求,将数据填充到

问题描述

我对 React Native 很陌生,虽然我可以将数据发送到 Mysql 数据库并且都使用 POST,但是我对向 REST apis 发出 GET 请求还是很陌生。

我有一个挑战是使用从表单获取的一些数据向 REST api 发出请求,并通过导航传递,因此我可以将值传递给第二个表单,然后传递到 API,然后使用 API 进行查询,返回 JSON 数据并显示在表格的某处。由于我是新手,我不知道如何使用 GET 请求,我只需要在这里解释一下。

我的代码看起来像这样

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class ShowAccountBalances extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

    
  componentDidMount()
  {
    const {navigation} = this.props;
        const username = navigation.getParam('user','NO-User');
    return fetch('http://192.168.1.100/api/persons/'+username, {
        method : 'GET',
    })
       .then((response) => response.json())
       .then((responseJson) => {
    
       this.setState({
       dataSource : responseJson.fullname,}, function(){
        });
    })
    .catch((error) => {
    console.error(error);
    });
  }

  render() {
    return (
      <View>
        <Text> Fullname : {this.fullname} </Text>
      </View>
    );
  }
}

标签: react-nativerestfetch

解决方案


根据您的代码,它this.fullName是从无处获取的。如果要从状态中获取,请更改为this.state.fullNameGET 请求的回调,并将状态设置为 fullName。

this.setState({fullName: responseJson.fullname});

并且您还需要像this.state = {fullName: ''}在构造函数中一样初始化 fullName 状态

并且您不必在 componentDidMount 中返回获取请求,只需在其回调中设置状态,react 将根据您的状态完成其余操作。


推荐阅读