react-native - 在 React Native 中获取未定义
问题描述
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class HttpExample extends Component {
state = {
data: ''
}
componentDidMount = () => {
fetch("https://jsonplaceholder.typicode.com/posts/1", { --this is fake url
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
}),
body: "param1=value1¶m2=value2" // <-- Post parameters
})
.then((response) =>
response.text()
)
.then((responseText) => {
alert(responseText.id);
this.setState({
data: responseText
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>
{this.state.data.id}
</Text>
</View>
)
}
}
export default HttpExample;
如果我在警报中使用警报(响应文本),我会得到 o/p,但是当我试图从我的对象中获取单个值时,它返回未定义
o / p:“id”:“1”,“computeId”:“USR00001”在警报中
解决方案
.then((response) => response.text())
至
.then((response) => response.json())
我猜你需要 json 风格的响应。
推荐阅读
- php - 替换字符串中的字符代码 8217 时 PHP 意外输出
- kotlin - 属性访问语法无法识别 Kotlin Safe Cast
- teradata - 是否有一种工具可以让用户查看他们的查询,但只能查看他们在 Teradata 上的查询?
- network-programming - NAT 中的 STUN 打孔不能随机工作
- elasticsearch - sql查询翻译查询DSL kibana
- gradle - 在多平台 js 和 jvm 项目中使用 kotlin-dce-js
- r - 在 R Shiny 界面中渲染 YouTube 链接
- python - 如何从文本中删除或分离表情符号(以“utf-8”编码),如下所示
- c# - 使用 WriteAllText 如何将 DataTable 列名写入 CSV 文件
- reactjs - useCallback 和 useMemo react hook 的缓存大小是多少,为什么?