【问题标题】:React typescript error Parsing error: '>' expected反应打字稿错误解析错误:'>'预期
【发布时间】:2023-04-01 21:53:02
【问题描述】:

我正在将 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”的另一个问题,但这是另一回事。

谢谢大家!

【问题讨论】:

  • 这是一个*.tsx 格式的文件。更改文件扩展名可能就足够了。
  • @Andreas_D 这就是我所做的。同样的错误。
  • @KevinB 你的意思是 {...rest}?不工作。
  • 不,我指的是箭头函数。然后意识到这是一条完全不同的路线。但我仍然认为这在某种程度上与问题有关
  • @Andreas_D 是的,语法存在问题,但只需更改间距和下一行,它就得到了修复。虽然不知道确切的语法问题。无论如何谢谢。

标签: reactjs typescript react-tsx


【解决方案1】:

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

【讨论】:

  • 好的,我更改为 tsx 并稍微更改了 tsx 返回的间距,它起作用了。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2018-03-06
    • 2013-08-20
    • 2021-01-08
    • 2016-06-19
    • 2017-09-27
    相关资源
    最近更新 更多