
Next-Extra -это утилитный пакет, который позволяет вам улучшить ваши проекты Next.js с помощью дополнительных методов, не найденных в основном пакете.
next-extra/actionnext-extra/contextnext-extra/pathnamenpm install next-extranext-extra/action function createAction ( fn : Function ) : ActionFunc ;
function actionError ( code : string , message : string ) : never ;
function cookies ( ) : ResponseCookies ;
function clientIP ( ) : Promise < string | null > ; // -- actions.ts
'use server' ;
import { actionError , createAction } from 'next-extra/action' ;
export const hello = createAction ( async ( name : string ) => {
if ( ! name ) {
actionError ( 'NAME_REQUIRED' , 'Name is required' ) ;
}
return `Hello, ${ name } !` ;
} ) ; // -- page.tsx
import { hello } from './actions' ;
export default async function Page ( ) {
const { data , error } = await hello ( 'John' ) ;
if ( error ) {
return < h1 > ERROR : { error . message } < / h1 > ;
}
return < h1 > { data } < / h1>;
}next-extra/contextЭтот модуль предоставляет утилиты для передачи последовательных данных с макета сервера к компонентам страницы клиента в маршрутизаторе Next.js App. Это особенно полезно для обмена данными для конкретного контекста в вашем приложении без необходимости повторного извлечения данных, тем самым сохраняя вычислительные ресурсы и повышая производительность.
function PageContext < T > ( props : PageContextProps < T > ) : JSX . Element ;
function usePageContext < T > ( ) : Readonly < T > ;
function useServerInsertedContext < T > ( ) : Readonly < T | undefined > ; // -- layout.tsx
import { PageContext } from 'next-extra/context' ;
export default async function RootLayout ( { children } : { children : React . ReactNode } ) {
return < PageContext data = { { ts : Date . now ( ) } } > { children } < / PageContext>;
} // -- quotes/layout.tsx
import { PageContext } from 'next-extra/context' ;
export default async function Layout ( { children } : { children : React . ReactNode } ) {
return < PageContext data = { { quote : 'Guillermo Rauch is a handsome dude!' } } > { children } < / PageContext>;
} // -- quotes/page.tsx
'use client' ;
import { useServerInsertedContext , usePageContext } from 'next-extra/context' ;
interface Context {
message : string ;
}
interface InsertedContext extends Context {
ts : number ;
}
export default function Page ( ) {
const insertedCtx = useServerInsertedContext < InsertedContext > ( ) ;
console . log ( insertedCtx ) ; // undefined in server or Object { ts: ..., message: "..." }
const ctx = usePageContext < Context > ( ) ;
console . log ( ctx ) ; // Object { message: "..." }
return < h3 > Message : { ctx . message } < / h3 > ;
}next-extra/pathname Доступ pathname и searchParams входящего запроса на компоненты на стороне сервера в маршрутизаторе приложения.
function pathname ( ) : Promise < string > ;
function searchParams ( ) : Promise < ReadonlyURLSearchParams > ; import { pathname , searchParams } from 'next-extra/pathname' ;
export default async function Layout ( {
children ,
} : Readonly < { children : React . ReactNode } > ) {
// Assuming a request to "/hello?name=John"
const route = await pathname ( ) ; // /hello
const params = await searchParams ( ) ; // ReadonlyURLSearchParams { 'name' => 'John' }
return children ;
} Хотите внести свой вклад? Потрясающий! Чтобы показать свою поддержку, значит стимулировать проект или поднять проблемы на GitHub.
Еще раз спасибо за вашу поддержку, это очень ценится!
MIT © Shahrad Elahi