简体   繁体   English

如何在使用 axios 获取的数组上进行 map

[英]How to map over an array that is fetched using axios

I am working on a chat-app and is trying to make a fetch using axios for the first time.我正在开发一个聊天应用程序,并尝试首次使用 axios 进行获取。 I have succeded in making the fetch because I see the array from the url when I console.logging it.我成功地进行了提取,因为当我控制台记录它时,我看到了来自 url 的数组。 However I want to map over all the messages in the array and display them for a user.但是我想对数组中的所有消息进行 map 并将它们显示给用户。 But I am doing something wrong so the mapping dosent work.但是我做错了,所以映射剂量起作用。 Can someone help me to see why?有人可以帮我看看为什么吗?

This is my code (I belive that its the map-function that is creating the problem):这是我的代码(我相信它是造成问题的地图功能):

import React, { useState, useEffect } from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import axios from 'axios'


export const GetMessages = () => {
  const [userName, setUserName] = useState([]);
  const [userMessage, setUserMessage] = useState([]);

  const fetchResponse = async () => {
    try {
      const getResponse = await axios.get(
      'http://167.172.108.61/?storage=camilla_lofroth'
    )
    console.log(getResponse)
    setUserMessage(getResponse)
    } catch (error) {
      alert('Error')
    }
    return[]
  }  

  useEffect(() => {
    fetchResponse()
  }, [])

  console.log(userMessage)

  return (
    <div>
      {userMessage.map(message => (
        <p>{message.message}</p>
      ))}
    </div>
  )
  }

Some of the response in the array is object which make React fail to render.数组中的一些响应是 object,这使得 React 无法渲染。 The 3rd to 5th items.第 3 项至第 5 项。

[
    {
        "message": "hej test"
    },
    {
        "message": "hej test",
        "id": "1"
    },
    {
        "message": {
            "mess": "Hi",
            "status": true
        }
    },
    {
        "message": {
            "mess": "Hi",
            "status": true
        }
    },
    {
        "message": {
            "mess": "Hi",
            "status": true
        }
    }
]

It seems like you have message as an object within the array.似乎您在数组中有消息作为 object 。 You must check if its an object and then render the required field您必须检查其是否为 object,然后呈现必填字段

import React, { useState, useEffect } from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import axios from 'axios'


export const GetMessages = () => {
  const [userName, setUserName] = useState([]);
  const [userMessage, setUserMessage] = useState([]);

  const fetchResponse = async () => {
    try {
      const getResponse = await axios.get(
      'http://167.172.108.61/?storage=camilla_lofroth'
    )
    console.log(getResponse)
    setUserMessage(getResponse)
    } catch (error) {
      alert('Error')
    }
    return[]
  }  

  useEffect(() => {
    fetchResponse()
  }, [])

  console.log(userMessage)

  return (
    <div>
      {userMessage.map(message => (
        <p>{message.message !== null && typeof message.message === 'object'? message.message.mess: message.message }</p>
      ))}
    </div>
  )
}

Actually when you use axios, the data returned is inside of an object called data.实际上,当您使用 axios 时,返回的数据在称为数据的 object 内部。 Just like like with the fetch API where you have to add .json() to the response, you also have to destructure the data out of axios response.就像获取 API 一样,您必须将 .json .json()添加到响应中,您还必须从 axios 响应中解构数据。

In your case, it should be something like this在你的情况下,它应该是这样的

const fetchResponse = async () => {
    try {
      const getResponse = await axios.get(
      'http://167.172.108.61/?storage=camilla_lofroth'
    )
    Const data = await getResponse.data
    Console.log(data)
    setUserMessage(data)
    } catch (error) {
      alert('Error')
    }
    return[]
  }  


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM