组件之间的强类型导航

时间:2018-07-20 09:41:52

标签: reactjs typescript react-router

我想确保在组件之间导航的URL是有效的并且是强类型的,这意味着:具有匹配的参数和查询字符串参数。因此,当组件更改其接受的URL时,它将破坏所有无效用法。我有一个潜在的解决方案,如下所示。 除了下面写的以外,还有解决我问题的更好的方法吗?我使用的是react-router 3,但是也欢迎使用4或其他软件包的解决方案。该解决方案必须支持链接到组件 y 和<的组件 x em> y 链接回 x

这是一个潜在的解决方案:

getSomeComponentUrl.ts

export interface ISomeComponentQuery {
    someArgument?: string;
    origin?: 'x' | 'y' | 'z';
}

export interface ISomeComponentParams {
    id?: string;
}

export const getSomeComponentUrl = (input: ISomeComponentQuery & ISomeComponentParams ) => 
    getUrlWithId('someComponentRootUrl', input);

getUrlWithId.ts

import { stringify } from 'query-string';

export function getUrlWithId(root: string, input: { id?: string }): string {
    const { id, ...queryStringParams } = input;
    if (!id) {
        throw Error(`"/${root}/" requires an id.`);
    }
    return `/${root}/${input.id}?${stringify(queryStringParams)}`;
}

someOtherComponent.ts

import { getSomeComponentUrl } from '../someComponent/getSomeComponentUrl';

getSomeComponentUrl({ id: item.id, origin: 'x', someArgument: this.someArgument });

此方法的缺点是必须为每个可以导航到的组件创建getSomeComponentUrl函数。

1 个答案:

答案 0 :(得分:0)

您可以在基础getSomeComponentUrl中提取class,使该函数成为通用类型,默认情况下,将扩展基类的所有组件都可以来回“导航”。该基类也可以实现专用的id字符串,以确保在创建组件时该字符串存在

但是提供具有键入功能的界面是您需要的最佳解决方案。

相关问题