react-native - 使用本机反应的 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>
);
}
}
解决方案
根据您的代码,它this.fullName
是从无处获取的。如果要从状态中获取,请更改为this.state.fullName
GET 请求的回调,并将状态设置为 fullName。
this.setState({fullName: responseJson.fullname});
并且您还需要像this.state = {fullName: ''}
在构造函数中一样初始化 fullName 状态
并且您不必在 componentDidMount 中返回获取请求,只需在其回调中设置状态,react 将根据您的状态完成其余操作。
推荐阅读
- python - 如何使用 NLTK 从 Python 中的文本字符串中提取数字
- excel - 如何使用表单(方法=发布)登录网站?
- python - PyQt 使用一键将温度转换为摄氏度和华氏度
- python - 比较两个图像(包含建筑物)的相似性的最有效方法是什么
- polymer - 根据纸张标签选择添加/删除铁选择类
- elasticsearch - Elasticsearch:search_as_you_type 数据类型与标记器 edge_ngram
- node.js - MongoDB:了解索引类型和索引属性
- svn - 将 Subversion 中的文件移动到限制较少的文件夹是否会暴露其版本和日志历史记录?
- python - 执行存储为字符串值的模块
- json - Pandas 数据框从 json 中提取值,从请求中作为内容(JSON)返回,