首页 > 解决方案 > 对象访问后变成字符串

问题描述

后端向前端发送一个对象。对象如下所示: {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 ?? ''});
        })
    }

标签: reactjsstringobject

解决方案


该属性似乎body是一个 JSON 字符串,因此您需要对其进行解析:

const items = JSON.parse(obj.body);

然后你可以映射items变量。


推荐阅读