【问题标题】:useState data not working with .map functionuseState 数据不适用于 .map 函数
【发布时间】:2021-11-07 10:57:51
【问题描述】:

我有一个从 API 获取博客文章的应用程序。带有博客文章的 API 响应,我将这些博客文章发送到 GetBlogState 状态。当我使用 .map 遍历 GetBlogState 时,出现以下错误。

以下是我目前正在使用的代码。

import React, { useState, useEffect } from 'react';
import Head from 'next/head'
import axios from 'axios'
import HeaderComponent from '../components/HeaderComponent';

export default function Blog(){

  const [GetBlogState, SetBlogState] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:4000/blog').then(res => {
      SetBlogState(res)
    }).catch(errr => {
      console.log(err)
    })
  }, []);

  return (
    <div className="MyApp">
        { GetBlogState.map(item => (
        <div className="h-68">
            <img className="w-full" alt="post" src='post.jpg' />
            <div className="mt-3 mb-2 text-xs">May 10, 2018</div>
            <h2 className="font-bold mb-5 text-xl"><a href="/" className="hover:underline">{ item.Title } </a></h2>
            <p>{item.content}</p>
        </div>
        ))}
    </div>
  )
}

【问题讨论】:

  • 检查res 变量。它可以是一个对象、null、字符串……并且只有数组有map。

标签: node.js reactjs express


【解决方案1】:

我认为你应该检查你从 axios 获得的 res 的输出。

您将响应对象设置为错误的状态。

你应该这样做

  useEffect(() => {
    axios.get('http://localhost:4000/blog').then(res => {
    //// console.log(res) Check whats returning in res \\\
       SetBlogState(res.data)
    }).catch(errr => {
      console.log(err)
    })
  }, []);

【讨论】:

  • 我现在因为忽略了这么一件小事而感到很愚蠢。谢谢。它现在正在工作。
  • @RedVirus 不用担心。每当您在编程中使用任何东西时。首先阅读文档。对你有很大帮助。
【解决方案2】:

Axios 的响应模式将服务器响应放在 data 中。因此设置状态如SetBlogState(res.data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多