Dữ liệu chung của các component trong NextJS
Có những tình huống khi nhiều component
cần truy cập vào cùng một dữ liệu.
Ví dụ, giả sử chúng ta có một mảng
người dùng nhất định. Giả sử trên một route
chúng ta muốn hiển thị danh sách người dùng,
còn trên route khác với tham số động -
mô tả một người dùng cụ thể theo id của họ.
Hãy triển khai điều đã mô tả. Chúng ta sẽ tạo cấu trúc tệp như sau:
- /app/
- /users/
- users.js
- /list/
- page.jsx
- /show/[id]/
- page.jsx
- /users/
Chúng ta sẽ tạo một tệp riêng với dữ liệu người dùng:
export default users = [
{
id: 1,
name: 'name1',
surn: 'surn1',
},
{
id: 2,
name: 'name2',
surn: 'surn2',
},
{
id: 3,
name: 'name3',
surn: 'surn3',
},
];
Chúng ta sẽ tạo một component để hiển thị danh sách người dùng:
import users from '../users.js';
export default function List() {
let list = users.map(user => {
return <li>
{user.name}
</li>;
});
return <ul>
{list}
</ul>;
}
Chúng ta sẽ tạo một component để hiển thị
một người dùng cụ thể theo id của họ:
import users from '../../users.js';
export default function User({params}) {
let user = users[params.id];
return <div>
<span>{user.id}</span>
<span>{user.name}</span>
<span>{user.surn}</span>
</div>;
}
Cho mảng sau:
let prods = [
{
id: 1,
name: 'prod1',
cost: 100,
desc: 'desc1',
},
{
id: 2,
name: 'prod2',
cost: 200,
desc: 'desc2',
},
{
id: 3,
name: 'prod3',
cost: 300,
desc: 'desc3',
},
];
Hãy tạo hai component. Giả sử component đầu tiên hiển thị danh sách sản phẩm, còn component thứ hai - mô tả chi tiết sản phẩm.