reactjs - 对象访问后变成字符串
问题描述
后端向前端发送一个对象。对象如下所示: {body: "Items":[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}], “计数”:2,“扫描计数”:2}
typeof(obj) 返回对象。
当我访问“body”时,typeof(obj["body"]) 返回一个字符串,我无法检索“Items”中的数组。
console.log(typeof(this.state.message)); // object
const obj = this.state.message;
console.log(obj["body"]); // string
我的最终目标是访问“Items”中的数据并将其转换为 render() 中的表。为什么我的对象会转换为字符串?
这是来自 Lambda 的后端代码:
async function listItems(){
try {
const data = await docClient.scan(params).promise()
return data
} catch (err) {
return err
}
}
exports.handler = async (event, context) => {
try {
const data = await listItems()
return { body: JSON.stringify(data) }
} catch (err) {
return { error: err }
}
}
这是 ReactJS 中的前端 Fetch 代码:
async getData() {
//this.setState({message: "test"})
await axios.get("https://...")
.then((response) => {
console.log((response));
console.log(typeof(response)); // object
this.setState({message: response?.data ?? ''});
})
}
解决方案
该属性似乎body
是一个 JSON 字符串,因此您需要对其进行解析:
const items = JSON.parse(obj.body);
然后你可以映射items
变量。
推荐阅读
- javascript - 使用 json 格式的数据制作 highcharts 图表,带有 4 元素数组
- react-native - 后台返回后调用函数
- python-3.x - 'list' 对象没有属性 'encode
- javascript - 在 TouchableHighlight 标记内包装图像标记无法正常工作
- javascript - 我正在尝试包含 simplepeer.js,但未找到显示 404 错误。相反,我给出了正确的道路
- javascript - 从 Firestore DocumentReferences 列表中获取数据到 State React
- c# - 当我从我的数据库中导入模型时,我希望我的数据库中的实例不在数据库模型中生成
- python - Django 将用户详细信息添加到 UserPost 列表视图
- json - 为令牌交换代码时获取 unsupported_grant_type
- grafana - Grafana + InfluxDB Flux - 用于显示多选变量输入的查询