首页 > 解决方案 > 如何使用 flowjs 从到达路由器键入 Match 组件

问题描述

类型定义是:

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 效果很好,但反应崩溃不能将 Class 作为函数调用。

const MatchAgent: Match<{id:string}> = Match;

这适用于反应,但不适用于流程:'(

有人知道我们如何用 flowjs 输入吗?谢谢

编辑:这是我的解决方法

  const MatchAgent = new Match<{ id: string }>({
    path: '/agents/:id',
    children: ({ match, navigate }) => ([...]),
  });

标签: javascripttypesflowtypereach-router

解决方案


如果我理解正确,您想match成为非null. 不幸的是,根据 Flow 类型的定义,match可以是null或形状的对象{ uri: string, path: string } & Params。为了让 Flow 停止抱怨matchbeing null,您需要match通过检查它是否是来进行改进null。例如,

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,则可以null从联合类型中删除match: { uri: string, path: string } & Params.


推荐阅读