使用Axios和React从API渲染单个记录

ldxq2e6h  于 5个月前  发布在  iOS
关注(0)|答案(1)|浏览(71)

使用Strapi作为后端,Axios和React,我尝试从记录列表中渲染单个记录(这里的列表没有问题)。对于单个记录,我使用useParams并完成API调用。我可以在控制台中看到我的数据。我的数据结构如下:


的数据
当我需要呈现上面的单个数据时,问题就来了。我得到一个错误,说:



这个错误我没有得到当我呈现我所有的记录,只有与特定的一个.因此,我不能正确地呈现这个特定的记录,我被困在这里.非常感谢您的帮助.这里是我的代码:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
import { Table, TableContainer, Thead, Td, Th, Tr, Tbody } from "@chakra-ui/react";

function ClubDisplay  () {
    const { id } = useParams();
    const [clubs, setClubs] = useState([]);
    useEffect(() => {
    axios.get('http://localhost:1337/api/adversaires/'+id)
        .then( res => {
          const fetchedClubs = res.id;
          setClubs(fetchedClubs);
          console.log(res)
        });
    }, []);
return (
    <TableContainer>
    <Table size='lg'>
        <Thead>
            <Tr>
                <Th>ID club</Th>
            </Tr>
        </Thead>
                <Tbody>
        {
        clubs.map((club, index) => {
            return <tr key={index}>
                <td>{club.id}</td>
            </tr>
            }
        )}                                                           
                </Tbody>
    </Table>
    </TableContainer>
)
}
export default ClubDisplay;

字符串

kx1ctssn

kx1ctssn1#

用这个更新你的代码:

const { id } = useParams();
const [club, setClub] = useState(null); // Single club object, not an array

useEffect(() => {
    axios.get(`http://localhost:1337/api/adversaires/${id}`)
        .then(res => {
            const fetchedClub = res.data.data; 
            setClub(fetchedClub);
            console.log(res);
        })
        .catch(error => {
            console.error("Error fetching club:", error);
        });
}, [id]);

    and also change :
   

      <TableContainer>
                <Table size='lg'>
                    <Thead>
                        <Tr>
                            <Th>ID club</Th>
                        </Tr>
                    </Thead>
                    <Tbody>
                        {club && ( // Conditional rendering to check if club exists or not 
                            <Tr>
                                <Td>{club.id}</Td>
                                
                            </Tr>
                        )}
                    </Tbody>
                </Table>
            </TableContainer>

字符串

相关问题