geo*_*tle 5 import dynamic typescript reactjs next.js
我正在使用 nextjs 应用程序。我想动态导入一个依赖于作为组件提供的路径的函数。今天,我使用函数的映射id,并使用路径中提供的 id 来检索该函数并在我的组件中使用它。然而,我怀疑这是否利用了代码分割。
这是一个说明我的观点的最小示例。不过,想象一下,这些函数并不像这里详细介绍的那么简单——想象一下,函数有很多,而且每个都很大,因此我们最好只发送渲染给客户端所需的函数。也就是说,在示例情况下,仅add当algoId路径中的 是add(并且其他 id 相同)时才发送。
import { FunctionComponent, ReactElement, useState } from "react";
import { GetStaticPaths, GetStaticPathsResult, GetStaticProps, GetStaticPropsResult } from "next";
import { ParsedUrlQuery } from "querystring";
import * as React from "react";
type MyAlgo = (a: number, b: number) => number;
const add: MyAlgo = (a: number, b: number): number => a + b;
const multiply: MyAlgo = (a: number, b: number): number => a * b;
const myAlgos: Map<string, MyAlgo> = new Map([["add", add], ["multiply", multiply]]);
interface MyParams extends ParsedUrlQuery {
algoId: string;
}
interface MyProps {
algoId: string;
}
export const getStaticPaths: GetStaticPaths<MyParams> = (): Promise<GetStaticPathsResult<MyParams>> => {
return Promise.resolve({
paths: [...myAlgos.keys()].map(algoId => ({ params: { algoId } })),
fallback: false
});
};
export const getStaticProps: GetStaticProps<MyProps, MyParams> =
({ params }): Promise<GetStaticPropsResult<MyProps>> => {
if (!params?.algoId) {
throw new Error("No algo id");
}
return Promise.resolve({
props: {
algoId: params.algoId,
}
});
};
const MyPage: FunctionComponent<MyProps> = ({ algoId }): ReactElement => {
const algo = myAlgos.get(algoId);
if (!algo) {
throw new Error(`No algo for algo id ${algoId}`);
}
const [a, setA] = useState(0);
const [b, setB] = useState(0);
const [res, setRes] = useState(0);
return <div>
<input
type="number"
placeholder="a"
onChange={(e) => {
setA(parseInt(e.target.value));
setRes(algo(a, b));
}}
/>
<input
type="number"
placeholder="b"
onChange={(e) => {
setB(parseInt(e.target.value));
setRes(algo(a, b));
}}
/>
<p>{res}</p>
</div>
};
export default MyPage;
Run Code Online (Sandbox Code Playgroud)
有没有办法实现客户端动态导入以利用代码分割?我注意到有一种方法可以动态导入组件,但这不是我正在寻找的。我希望组件对于该页面类型保持不变,并且我的函数根据路径而变化。
谢谢。
| 归档时间: |
|
| 查看次数: |
440 次 |
| 最近记录: |