当我为自定义历史添加参数时,我在React中遇到以下错误:
<Router history={history}>
我从ESLint收到此错误:
[eslint] Parsing error: Unexpected token =
(JSX attribute) history: History<any>
这是我的.eslintrc.js文件:
export default {
parser: 'babel-eslint',
extends: 'airbnb',
parserOptions: {
ecmaVersion: 8,
ecmaFeatures: {
jsx: true,
modules: true,
},
},
env: {
node: true,
browser: true,
jest: true,
mongo: true,
},
rules: {
'no-unused-vars': [
'error',
{
vars: 'local',
args: 'none',
},
],
'react/jsx-filename-extension': 0,
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: true,
},
],
},
};
和我的package.json文件:
"devDependencies": {
"babel-eslint": "^10.0.1",
"eslint": "^5.3.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.15.0",
"eslint-plugin-jsx-a11y": "^6.2.0",
"eslint-plugin-react": "^7.12.4"
},
"eslintConfig": {
"extends": "react-app"
}
最后是AppRouter.js文件:
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import Home from '../components/HomePage';
import NotFound from '../components/NotFoundPage';
export const history = createHistory();
const AppRouter = () => (
<Router history={history}>
<div>
<Switch>
<Route path="/" component={Home} exact={true} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
export default AppRouter;
答案 0 :(得分:2)
请尝试导入/使用特定的更高级别的浏览器/ DOM路由器,例如BrowserRouter。您甚至可以将其别名为Router
或任何您喜欢的名称。如果您参考Router的文档,则建议使用更高级别的路由器,例如上述BrowserRouter
。另外,如果您查看Router
文档,则会发现Router
也不是从react-router-dom
导入的,而是从react-router
导入的,这很可能是发生特定错误的原因
BrowserRouter
的好处还可以自动为您创建历史记录,因此您无需手动createHistory()
:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from '../components/HomePage';
import NotFound from '../components/NotFoundPage';
const AppRouter = () => (
<Router history={history}>
<div>
<Switch>
<Route path="/" component={Home} exact={true} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
export default AppRouter;
否则,如果您需要手动创建历史记录或使用较低级别的路由器,请从Router
导入react-router
:
import React from 'react';
import { Router } from 'react-router';
import { Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import Home from '../components/HomePage';
import NotFound from '../components/NotFoundPage';
export const history = createHistory();
const AppRouter = () => (
<Router history={history}>
<div>
<Switch>
<Route path="/" component={Home} exact={true} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
export default AppRouter;
希望有帮助!