类型定义是:
declare export class Match<Params> extends React$Component<{|
path: string,
children: (props: {|
match: null | ({ uri: string, path: string } & Params),
location: typeof location,
navigate: NavigateFn,
|}) => React$Node,
|}> {}
像这样使用匹配:
<Match path="/agents/:id">
{({ match, navigate }) => ( [...] )
</Match>
这里match
被认为是按流null
如果我尝试类似的东西
class MatchAgent extends Match<{id: string}> {}
flow 效果很好,但 React 崩溃不能将类调用为函数。
const MatchAgent: Match<{id:string}> = Match;
这适用于 react,但不适用于 flow :'(
有人知道我们如何用 flowjs 键入它吗? 谢谢
编辑:这是我的解决方法
const MatchAgent = new Match<{ id: string }>({
path: '/agents/:id',
children: ({ match, navigate }) => ([...]),
});
如果我理解正确,您希望match
是非null
的。不幸的是,根据流类型定义,match
可以是null
或形状{ uri: string, path: string } & Params
的对象。要让 Flow 停止抱怨match
null
,您需要通过检查它是否null
来优化match
。例如
import React from 'react';
declare export class Match<Params> extends React$Component<{|
path: string,
children: (props: {|
match: null | ({ uri: string, path: string } & Params),
location: any, // since location isn't defined in Try Flow
navigate: any, // since NavigateFn isn't defined in Try Flow
|}) => React$Node,
|}> {}
function App() {
return (
<Match path="/agents/:id">
{({ match, navigate }) => {
if (match === null) {
return null; // or whatever you want when it doesn't match
}
return match.id;
}}
</Match>
);
}
尝试流
或者,如果您控制了Match
的 Flow 类型定义(和实现),则可以从联合类型中删除null
,match: { uri: string, path: string } & Params
。