【发布时间】: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