React-迁移到React Router 4

时间:2019-02-14 00:25:58

标签: reactjs react-router react-router-v4

我正在将我的React App从React-Router-3迁移到React-Router-4,并且遇到了一些问题。我的应用程序的布局如下。

build
node_modules
public
src
  AboutScreen
  ContactScreen
  HomeScreen
  LoginScreen
  SignUpScreen
  WorkRequestScreen
  App.js
  index.js
  routes.js
  serviceWorker.js
package.json
package-lock.json

我遇到以下错误:

  

./ src / index.js:第8行:意外使用“历史记录”无限制全局变量

history={history}中删除index.js时,出现以下错误。

  

TypeError:无法读取未定义的属性“位置”

我一直按照以下教程从3迁移到4。

  

https://codeburst.io/react-router-v4-unofficial-migration-guide-5a370b8905a

我的route.js如下:

import React from 'react';
import { Route, Redirect, Router, Switch } from 'react-router-dom';
import createHashHistory from 'history/createHashHistory';
import App from './App';

import Home from './HomeScreen/Home';
import WorkReq from './WorkRequestScreen/WorkReq';
import About from './AboutScreen/About';
import Contact from './ContactScreen/Contact';
import Login from './LoginScreen/Login';
import Signup from './SignUpScreen/Signup';

const history = createHashHistory();
const routes = () => (
  <Router history={history}>
    <Switch>
      <Route exact path="/workReq" component={WorkReq}/>
      <Route exact path="/about" component={About}/>
      <Route exact path="/contact" component={Contact}/>
      <Route exact path="/login" component={Login}/>
      <Route exact path="/signup" component={Signup}/>
      <Route exact path="/" component={Home}/>
    </Switch>
  </Router>
);

export default routes;

我的index.js如下:

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';

import { Route, Redirect, Router, Switch } from 'react-router-dom';
import routes from './routes'; 

ReactDOM.render(<Router history={history} routes={routes}/>, 
document.getElementById('root'));

serviceWorker.unregister();

1 个答案:

答案 0 :(得分:0)

不需要显式地传递历史记录,因为Route作为道具隐式地传递了history 1

我将从history中删除传递给Router的{​​{1}}道具,并从index.js中的Router中删除它