react native数据传输的格式问题

两种传输问题:

1,前后台之间数据传输,格式正常来说有三种:XML,HTML,JSON;react native使用JSON;其他的可以看链接:https://www.cnblogs.com/realshijing/p/8401294.html
2,两个页面之间数据传输的方式有两种:this.state和AsyncStorage传输;

第一种(php推送数据到react)

1,后台传输过来的数据为JSON格式的字符串
echo ’ { “name”: “bob” , “age”: 11 , “array” : [ 1,2,3,4] } ’ ;
2,react使用fetch接收到的自然也是JSON格式的字符串:
react解析此数据,首先需要将数据转化为JSON对象(JSON.parse() ),然后进行属性调用 (obj.name) :
fetch(url, options).then((response)=>response.json() ) .then((result)=> result.name ) //response.json()相当于执行了JSON.parse(response);

第一种 (react向php推送数据)

1,react传送过来的数据为JSON格式的字符串:
options={
body:JSON.stringify({
“name”: this.state.name,
“age”: 11,
})
2,php接收的也是JSON格式的字符串:
首先也是要把JSON字符串转化为JSON对象,然后调用对象的属性进行数据解析:
$data=file_get_contents(“php://input”) ; //由于react没有get,post这种数据提交方式,只能用普遍获取数据的方式。
o b j d a t a = j s o n d e c o d e ( objdata=json_decode( data); //将json格式字符串解析为json格式的对象。
n a m e = name= objdata->name; / /php调用对象的方式 obj->age;

第二种(两个页面之间传值使用this.state:):

1,发送数据的页面:
a页面将数据存储到本地的state中,随着页面跳转作为参数携带到b页面,
this.state={
“name”: “bob”,
“age”: 11,
}
this.props.navigation.navigate(“App2” , {
params1: this.state.name,
params2:this.state.age,
} ) //第二个参数是放传递的数据滴;
2,接收数据的页面:
this.props.navigation.getParam( ‘params1’) ; //获得了第一个参数数据;

第二种(两个页面之间传值使用AsyncStorage)

1,a页面向本地存储一个值:
AsyncStorage.setItem(‘name’ ,‘bob’ );
2,b页面获取这个值:
AsyncStorage.getItem("name“).then((result)=>{
Alert.alert(result); // bob
})

注: AsyncStorage会将数据存储在 RocksDB 或者 SQLite ,具体存储在 RocksDB 中还是SQLite中这取决于设备支持哪一种存储方式。具体链接:https://blog.csdn.net/teagreen_red/article/details/78543900

猜你喜欢

转载自blog.csdn.net/kalinux/article/details/88798440