gpt4 book ai didi

reactjs - 使用 Flow 和 redux-navigation 验证通用 React 组件属性

转载 作者:行者123 更新时间:2023-12-03 14:31:29 26 4
gpt4 key购买 nike

我正在尝试验证在调度新的屏幕操作时 React 组件是否接收到正确的属性。

路线可能如下所示。

class MyCompAB extends React.Component<{a: number, b: string}> {}
class MyCompCD extends React.Component<{c: number, d: string}> {}
const myRoutes = {'/ab': MyCompAB, '/cd': MyCompCD};

我需要的是这样的东西。我只是还没有找到让 openScreen 验证 props 对于 paths[name] 有好处的方法。

type Screen<P> = ComponentType<P>;
type Routes<P> = {[key: string]: Screen<P>};

function openScreen<P, R: Routes<mixed>, K: $Keys<R>>(routes: R, name: K, props: P): void {
// This needs to validate that props are valid for the component in routes[name].
// This won't do <Component {...props} />. Instead redux dispatch magic happens here.
type Pepe = $Call<R<P>, K>;
}

// $ExpectError. Should fail: a and b missing.
openScreen(myRoutes, '/ab', {});
// $ExpectError. Should fail: b has wrong type.
openScreen(myRoutes, '/ab', {a: 1, b: 1});
// Should work.
openScreen(myRoutes, '/ab', {a: 1, b: "1"});

// $ExpectError. Should fail: c and d missing.
openScreen(myRoutes, '/cd', {});
// $ExpectError. Should fail: d has wrong type.
openScreen(myRoutes, '/cd', {c: 1, d: 1});
// Should work.
openScreen(myRoutes, '/cd', {c: 1, d: "1"});

我该如何完成这项工作?

最佳答案

您可以使用function overloading对于像这样稍微次优的解决方案:

declare function openScreen<P: $PropertyType<MyCompAB, 'props'>, R: Routes<mixed>, K: '/ab'>(routes: R, name: K, props: P): void {

}

declare function openScreen<P: $PropertyType<MyCompCD, 'props'>, R: Routes<mixed>, K: '/bc'>(routes: R, name: K, props: P): void {

}

关于reactjs - 使用 Flow 和 redux-navigation 验证通用 React 组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51769335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com