React .map 不渲染

React .map not rendering

我调用了 API 来获取一些数据,然后将其存储在数组中,并在 return

中执行 .map

这就是代码,如果你们有任何想法,我已经坚持了 2 个小时 :(

import {useEffect, useState} from 'react';
import {useParams} from "react-router-dom";
import axios from "axios";


const CharacterScreen = () => {
    const params = useParams()
    const [character, setCharacter] = useState([]);
    const [starships, setStarships] = useState([]);


    useEffect(() => {
        axios.get(`https://swapi.dev/api/people/?search=${params.character}`)
            .then((r) => {
                setCharacter(r.data.results[0])
                getStarships(r.data.results[0])
            })
            .catch((e) => console.log(e))

        const getStarships = (data) => {
            let array = []
            data.starships.forEach(element => {
                axios.get(element)
                    .then((r) => {
                        array.push(r.data)
                    })
                    .catch((e) => console.log(e))
            })
            console.log(array)
            setStarships(array)
        }
    }, []);

    console.log(starships)
    return (
        <div>
            <p>{character.name}</p>
            <p>{character.eye_color}</p>
            <p>{character.birth_year}</p>
            <p>{character.gender}</p>
            <p>{character.created}</p>
            <p>{character.edited}</p>
            {starships.map((element) => {
                console.log('ok')
                return (
                    <p key={element.key}>{element.name}</p>
                )
            })}

        </div>
    )


}

这是星舰的.log :

这是我的 return :

如有任何帮助,我们将不胜感激

forEach 中的代码将 运行 异步。您将不得不等待所有数据实际填充到您的 array 中。 async/await pattern + Promise.all(..) 在这里是个不错的选择,可以这样做:-

const getStarships = async (data) => {
  let array = await Promise.all(data.starships.map(element => {
    return axios.get(element)
      .then((r) => {
        return r.data
      })
      .catch((e) => console.log(e));
  }))
  setStarships(array);
}

当前在您的代码中,当您执行 setStarships(array) 时,array 将为空,即 []

检查这个 codesandbox 它在哪里工作:-

注意:- 不要注意 element.replace 代码,那只是为了发出安全请求

你有一个语法错误,你应该用括号替换括号,如下所示:

{starship && starships.map((element) => (//here
                console.log('ok')
                return (
                    <p key={element.key}>{element.name}</p>
                )
            )//and here)}

使用展开运算符:

useEffect(() => {
        axios.get(`https://swapi.dev/api/people/?search=${params.character}`)
            .then((r) => {
                setCharacter(r.data.results[0])
                getStarships(r.data.results[0])
            })
            .catch((e) => console.log(e))

        const getStarships = (data) => {
            let array = []
            data.starships.forEach(element => {
                axios.get(element)
                    .then((r) => {
                        array.push(r.data)
                    })
                    .catch((e) => console.log(e))
            }) 
            setStarships([...array]) <=== //spread opeator
        }
    }, []);