Next.js Tutorial - Part 3 - TypeScript Migration getInitialProps 3

Nếu không sử dụng useEffect thì lần đầu vào link nó sẽ trắng trang :)))

C:\Users\Administrator\Desktop\nextjs\pages\list.tsx

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

C:\Users\Administrator\Desktop\nextjs\pages[vehicle][person].tsx

import fetch from 'isomorphic-unfetch';
import { NextPageContext } from 'next';
import { useEffect, useState } from 'react';
export interface PersonProps {
  ownersList?: VehiclePerson[];
}
export default function Person({ ownersList }: PersonProps) {
	const [owners, setOwners] = useState(ownersList);
	return <pre>{owners[0]?.details}</pre>;
}
Person.getInitialProps = async ({query, req}: NextPageContext) => {
	console.log(query);
	if (!req) {
    return { ownersList: [] };
  }
  const response = await fetch( 'http://localhost:3000/vehicles?ownerName=' + query.person + '&vehicle=' + query.vehicle);
  const ownersList: VehiclePerson[] | undefined = await response.json();
  return { ownersList };
}

Last updated

Was this helpful?