【问题标题】:Parse Nested JSON Using Axios and Async/Await使用 Axios 和 Async/Await 解析嵌套的 JSON
【发布时间】:2020-03-07 23:47:25
【问题描述】:

我正在尝试从 api 获取数据,该 api 应该返回一个带有一组食谱的 json 对象。我在前端使用 React hooks 和 Axios 来执行请求。钩子运行,但在尝试从响应中访问 json 数组时出现错误。

这是示例 api 响应:

{
    count: 30,
    recipes: [objects, ... 29]
}

和我的获取配方响应的代码:

const fetchRecipes = async () => {
    try {
        const recipeData = await Axios.get(api);
        console.log(recipeData);
        const recipes = await recipeData.json(); // error occurs here
        setRecipes(recipes);
        setLoading(false);
    } catch (err) {
        console.log(`Error occurred fetching recipes ${err}`)
    }
};

useEffect(() => {
    fetchRecipes();
}, []);

我已经删除了钩子声明,api url 是https://api.myjson.com/bins/t7szj。问题在于从响应中获取数组。我的 api 调用有问题吗?

这是错误信息:

Error occurred fetching recipes TypeError: recipeData.json is not a function

【问题讨论】:

    标签: reactjs async-await axios es6-promise react-hooks


    【解决方案1】:

    你试过了吗?

    const fetchRecipes = async () => {
        try {
            const recipeData = await Axios.get(api);
            console.log(recipeData.data);
            const recipes = recipeData.data;
            setRecipes(recipes);
            setLoading(false);
        } catch (err) {
            console.log(`Error occurred fetching recipes ${err}`)
        }
    };
    
    

    在使用 axios(与 fetch 不同)时,您不必在响应上调用 res.json(),因为 axios 会自动为您处理。这意味着 axios 默认将响应解析为 JSON。

    async/await with Axios

    【讨论】:

    • 现在可以使用了。但为什么它不适用于 .json() ?
    • @DarthPlagueris 我已经更新了代码:)。此外,async/await 增加了代码的可读性。我是async/await的粉丝。
    • 好的,非常感谢您的解释。我在病了一个月后正在复习,想了解我的基础知识,然后在参加面试之前了解更多。这绝对是一个很好的提示先生。非常感谢。
    • 很高兴它对您有所帮助。祝你即将到来的面试:)
    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2019-03-12
    • 2018-07-05
    • 1970-01-01
    • 2021-05-10
    • 2018-12-26
    • 2023-03-14
    • 2018-06-04
    相关资源
    最近更新 更多