Aquí está mi código:
import Base from "./Base"; import axios from "axios"; import { createData } from "../../utils"; import { useState, useEffect } from "react"; export default function Today(props) { const [scoops, setScoops] = useState(0); //Fetch api/scoops/today const fetchScoops = async () => { const res = await axios.get("http://localhost:8000/api/scoops/today/"); setScoops(res.data); }; useEffect(() => { fetchScoops(); }, []); console.log(scoops[0]); const rows = [ createData(0, 1, scoops[0].title, "http://example.com"), createData(1, 2, "Paul McCartney", "http://example.com"), createData(2, 3, "Tom Scholz", "http://example.com"), createData(3, 4, "Michael Jackson", "http://example.com"), createData(4, 5, "Bruce Springsteen", "http://example.com"), ]; return <Base rows={rows} duration="Today" />; }Esto es lo que devuelve la consola:
> undefined > Today.js:20 {url: 'http://localhost:8000/api/scoops/1/', title: 'Hello World!', rank: 0, created_at: '2021-10-05T04:44:52.027336Z', updated_at: '2021-10-05T04:44:52.027336Z'}El problema es que cuando actualizo la página, aparece el siguiente mensaje de error:
TypeError: Cannot read properties of undefined (reading 'title')¡La ayuda sería muy apreciada!
Actualización : el encadenamiento opcional resolvió el problema, esto funciona muy bien.
scoops[0]?.titlePuede establecer el estado inicial de scoops en []
const [scoops, setScoops] = useState([]); renderizar scoops cuando se obtienen datos usando conditionalRendering
return <> {scoops.lenght > 0 && <Base rows={rows} duration="Today" />} </>;El problema es que está inicializando scoops como 0 pero usándolo como una matriz: scoops[0]
Intente inicializar scoops como una matriz vacía. Así que algo como esto debería funcionar:
const [scoops, setScoops] = useState([]); Además, donde está haciendo esto: scoops[0].title , en su lugar, debe usar el encadenamiento opcional y usar scoops[0]?.title .title