GET请求与反应本机,填充数据以<Text>



我对React Native很陌生,虽然我可以使用POST将数据发送到Mysql数据库,但我对向RESTAPI发出GET请求很陌生。

我面临的挑战是使用从表单获得的一些数据向RESTAPI发出请求,并通过导航传递,这样我就可以将值传递到第二个表单,然后传递到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是从任何地方获取的。如果要从state获取,请更改为this.state.fullName,对于get请求的回调,请将state设置为fullName。

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

您还需要初始化fullName状态,如构造函数中的this.state = {fullName: ''}

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

最新更新