我有一个项目,在这个项目中我有一个登录页面,我想使用“RouteComponentProps”,但我收到了这个错误:
Module '"react-router-dom"' has no exported member 'RouteComponentProps'.
我尝试通过“react-router”导入它,但在我看来:
Module '"react-router"' has no exported member 'RouteComponentProps'.
我该如何解决这个问题?
这是我使用的“RouteComponentProps”文件的一部分:
signin.tsx:
import { RouteComponentProps } from 'react-router-dom';
interface Props {
history: RouteComponentProps['history']
}
package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.12.3",
"@material-ui/icons": "^4.11.2",
"@material-ui/styles": "^4.11.4",
"@reach/router": "^1.3.4",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.24",
"@types/node": "^12.20.37",
"@types/react": "^17.0.37",
"@types/react-dom": "^17.0.11",
"@types/react-redux": "^7.1.20",
"axios": "^0.24.0",
"history": "^5.1.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"react-router": "^6.1.1",
"react-router-dom": "^6.1.1",
"react-scripts": "4.0.3",
"redux": "^4.1.2",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.4.1",
"thunk": "0.0.1",
"typescript": "^4.5.2",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/react-router": "^5.1.17",
"@types/react-router-dom": "^5.3.2",
"miragejs": "^0.1.43"
}
}
react-router
v6 不再使用 RouteComponentProps
。以下是一些链接,其中包含有关 如何更改路线 和 如何在 v6 上使用参数 的示例,以及一些链接,您可以在其中找到更多信息:
用于更改路线(旧历史记录.push)
登录成功后如果想更改路由react-router文档指定
在 v6 中,应重写此应用程序以使用导航 API。大多数时候,这意味着将 useHistory 更改为 useNavigate 并更改history.push 或history.replace 调用站点。
所以基本上代替这个
...
function handleClick() {
history.push("/home");
}
...
使用类似的东西:
// This is a React Router v6 app
import { useNavigate } from "react-router-dom";
function App() {
let navigate = useNavigate();
function handleClick() {
navigate("/home");
}
...
对于链接参数
根据此链接,当您升级到React Router v6时,您应该只使用
import {useParams} from 'react-router-dom';
+ const params = useParams();
,如下所示:
import React from 'react';
import {useParams} from 'react-router-dom';
const Component: React.FC = (): JSX.Element => {
const params = useParams();
return <>Link ID parameter === "{params.id}"</>;
}
编辑有关类型(对于 ts): 您可以在此处找到有关接口的更多信息(用于 useNavigate) 以及 另一个潜在有趣的主题这里和这里(用于useParams)
import { Redirect } from "react-router-dom";
新版本
import { useNavigate } from "react-router-dom";