[ERROR] Sửa lỗi TypeError: Cannot read property 'details' of undefined (ok)

C:\Users\Administrator\Desktop\abc\pages[vehicle][person].js

import { useRouter } from 'next/router';
Person.getInitialProps = async ctx => {
  if (!ctx.req) {
    return { ownersList: [] };
  }
  const { query } = ctx;
  const response = await fetch(
    'http://localhost:3000/vehicles?ownerName=' + query.person + '&vehicle=' + query.vehicle
  );
  const ownersList = await response.json();
  return { ownersList };
};
export default function Person({ ownersList }) {
  return <h2>{ownersList[0].details}</h2>
}

Ta chỉ việc thêm dấu ? vào đằng sau chỗ báo lỗi :)))

return <h2>{ownersList[0]?.details}</h2>

C:\Users\Administrator\Desktop\abc\pages\list.js

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';
export default function List({ownersList}) {
  return (
    <div>
      {ownersList.map((e, index) => (
        <div key={index}>
          <Link as={`/${e.vehicle}/${e.ownerName}`} href="/[vehicle]/[person]">
            <a>
              Navigate to {e.ownerName}'s {e.vehicle}
            </a>
          </Link>
        </div>
      ))}
    </div>
  );
}
List.getInitialProps = async () => {
  const response = await fetch('http://localhost:3000/vehicles');
  const ownersList = await response.json();
  return {ownersList};
}

Nhưng lại có vấn đề sảy ra khi click vô link thì nó lại hiện ra trang trắng :)) cách khắc phục sau sẽ giải quyết

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
export default function Person({ ownersList }) {
  const router = useRouter();
 const [owners, setOwners] = useState(ownersList);
  useEffect(() => {
    async function loadData() {
      const response = await fetch('http://localhost:3000/vehicles?ownerName=' +
      router.query.person +
      '&vehicle=' +
      router.query.vehicle);
      const ownersList = await response.json();
      setOwners(ownersList);
    }
    if(ownersList.length == 0) {
        loadData();
    }
  }, []);
  if(!owners[0]) { 
      return <div>loading...</div>
  }
  return <pre>{owners[0]?.details}</pre>;
}
Person.getInitialProps = async ctx => {
    if(!ctx.req) {
        return { ownersList: [] };
    }
  const { query } = ctx;
  const response = await fetch(
    'http://localhost:3000/vehicles?ownerName=' + query.person + '&vehicle=' + query.vehicle
  );
  const ownersList = await response.json();
  return { ownersList: ownersList };
};

C:\Users\Administrator\Desktop\abc\db.json

{
    "vehicles": [
      {
        "vehicle": "Car",
        "ownerName": "Bruno Antunes",
        "details": "some detail about Bruno's Car"
      },
      {
        "vehicle": "Bike",
        "ownerName": "Bruno Antunes",
        "details": "some detail about Bruno's Bike"
      },
      {
        "vehicle": "Bike",
        "ownerName": "John Doe",
        "details": "some detail bile"
      },
      {
        "vehicle": "Airplane",
        "ownerName": "Bill Gates",
        "details": "some detail Bill Gates"
      } ,
      {
        "vehicle": "SpaceX",
        "ownerName": "Elon Musk",
        "details": "some detail Elon"
      }      
    ]
  }

C:\Users\Administrator\Desktop\abc\package.json

{
  "name": "abc",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "json": "json-server --watch db.json",
    "dev": "next dev -p 5000",
    "build": "next build && next export",
    "start": "next start"
  },
  "dependencies": {
    "isomorphic-unfetch": "^3.1.0",
    "next": "10.0.3",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  }
}

Last updated

Was this helpful?