首页 > 解决方案 > JSON 数据错误,无法读取未定义的属性

问题描述

我正在尝试从我的 API 中获取内容。内容存储为需要显示的 HTML。如何在每个键没有一个字符的情况下显示内容:

const getContent = async () => {
    try {
        const response = await getItem(KEY);
        console.log(JSON.parse(response))
        return JSON.parse(response);
    } catch (e) {
        logger.error('Error getting content', e);
        throw e;
    }
};

回复:

{66:“<”,67:“/”,68:“h”,69:“2”,70:“>”,71:“<”,72:“u”,73:“l”,74 : ">", 75: "<", 76: "l", 77: "i", 78:">", 79: "P", 80: "u", 81: "l", 82: " l", 83: " ", 84: "o", 85: "v", 86: "e", 87: "r", 88: " ", 89: "s", 90: "a", 91 :“f”,92:“e”,93:“l”,94:“y”,95:“<”,96:“/”,97:“l”,98:“i”,99:“ >", …}

然后我的减速器给了我这个错误:

TypeError:无法读取未定义的属性“informationOverlay”:

case CONTENT_SUCCESS:
{
  return {
    ...state,
    informationOverlay: action.payload.informationOverlay,
    loading: false,
  };
}

const getItem = async (key) => {
    try {
        const result = await AsyncStorage.getItem(key);
        return result;
    } catch (e) {
        logger.error('getItem', e);
        throw e;
    }
};

标签: javascriptjson

解决方案


您可以使用Object.values(JSON.parse(response)).join(''),但改进响应可能是一个更好的主意。


推荐阅读