反应打字稿错误分析错误:预期为'>'

时间:2020-02-27 16:58:30

标签: reactjs typescript react-tsx

我正在将js迁移到ts,修改后的代码有错误:

第26:8行:解析错误:预计为“>”

import React from "react";
import { Route, Redirect, RouteProps } from "react-router-dom";
import {render} from "react-dom"
import {AppProps} from "../App"

function querystring(name: string, url = window.location.href) {
  name = name.replace(/[[]]/g, "\\$&");

  const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i");
  const results = regex.exec(url);

  if (!results) {
    return null;
  }
  if (!results[2]) {
    return "";
  }

  return decodeURIComponent(results[2].replace(/\+/g, " "));
}
export default function UnauthenticatedRoute({ component: C, appProps, ...rest }:
                                                 RouteProps & {appProps: AppProps}) {
  const redirect = querystring("redirect");
  return (
    <Route
        {...rest} // the issue is here
        render={ props => !appProps.isAuthenticated ?
            <C {...props} {...appProps} />
          :
            <Redirect to={redirect === "" || redirect === null ? "/" : redirect}/>
    }
    />
  );
}

如果有人看到问题,那就好了:)。谢谢!


解决方案

1 /文件必须具有tsx扩展名

2 / tsx语法中的语法也有误。我改成了这个,现在可以了:

export default function UnauthenticatedRoute({ component: C, appProps, ...rest }:
                                                 RouteProps & {appProps: AppProps}) {
  const redirect = querystring("redirect");
  return (
    <Route {...rest}
        render={ props => !appProps.isAuthenticated ?
            <C {...props} {...appProps} />
          :
            <Redirect to={redirect === "" || redirect === null ? "/" : redirect}/>
        }
    />
  );
}

现在,绑定元素'C'还有另一个问题,但这是另外一回事了。

谢谢大家!

2 个答案:

答案 0 :(得分:8)

将文件扩展名从.ts更改为.tsx

答案 1 :(得分:0)

请注意:返回 react-dom 时,请始终使用 TSX,否则使用 TS