Cách 1: Dùng với cách thông thường giống với ReactJs :(
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';
export default function List({ownersList}) {
const [owners, setOwners] = useState([]);
useEffect(() => {
async function loadData() {
const response = await fetch('http://localhost:3000/vehicles');
const ownersList = await response.json();
setOwners(ownersList);
}
loadData();
}, []);
return (
<div>
{owners.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>
);
}
import { useRouter } from 'next/router';
export default function Person() {
const router = useRouter();
console.log(router.query);
return <h2>{router.query.person}'s {router.query.vehicle}</h2>
}
{
"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"
}
]
}
{
"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"
}
}
Cách 2: Dùng với cách của Next.js là sử dụng getInitialProps
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import fetch from 'isomorphic-unfetch';
export default function List({ownersList}) {
// const [owners, setOwners] = useState([]);
// useEffect(() => {
// async function loadData() {
// const response = await fetch('http://localhost:4001/vehicles');
// const ownersList = await response.json();
// setOwners(ownersList);
// }
// loadData();
// }, []);
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}
}