关于reactjs:添加createBrowserHistory后反应路由器,该应用程序无法按预期运行

React router after adding createBrowserHistory, the app is not working as expected

我将1-rc版本用于react路由器。 我的路线配置如下所示:

1
2
3
4
5
6
7
<Router>
  <Route path="/" component={App}>
    <IndexRoute component={About} />
    <Route path="about" component={About} />        
    <Route path="user" component={User} />      
  </Route>
</Router>

访问URL如下所示:
http:// localhost:3001 / assets#(入口点)
http:// localhost:3001 / assets#/ about?_k = 3mr0ay

但是,当我向路由添加createBrowserHistory支持时:

1
2
3
4
5
6
7
<Router history={createBrowserHistory()}>
  <Route path="assets/" component={App}>
    <IndexRoute component={About} />
    <Route path="about" component={About} />        
    <Route path="user" component={User} />      
  </Route>
</Router>

该应用程序无法正常运行。

错误是:

Warning: Location"/assets" did not match any routes

甚至我将/ assets添加到仍然无法使用的路径。

正确的做法是什么?


RC1中有几项新功能,其中之一是历史记录现在被分离到另一个存储库中,因此您不再从React Router本身中import删除它。 而是使用History。 因此,您需要npm install history

另外,请确保删除node_modules并在迁移到1.0.0-rc1时再次安装它们:

rm -rf node_modules && npm install

我只是为您提供示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import React, { PropTypes, Component } from 'react';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Router, Route, Link, IndexRoute } from 'react-router';

class Navigation extends Component {
  render() {
    return (
     
       
<ul>

         
<li>
<Link to='/'>Main</Link>
</li>

         
<li>
<Link to='/about'>About</Link>
</li>

         
<li>
<Link to='/contact'>Contact</Link>
</li>

       
</ul>

     
    );
  }
};

class Contact extends Component {
  render() {
    return Contact;
  }
}

class About extends Component {
  render() {
    return ( About );
  }
}

class Home extends Component {
  render() {
    return Home;
  }
}

class App extends Component {
  render() {
    return (
     
        App
        <Navigation />
        {this.props.children}
     
    );
  }
}

export default class Root extends Component {
  render() {
    return (
      <Router history={createBrowserHistory()}>
        <Route path='/' component={App}>
          <IndexRoute component={Home} />
          <Route path='about' component={About} />
          <Route path='contact' component={Contact} />
        </Route>
      </Router>
    );
  }
}

更多内容可以在《 React Router》文档和《升级指南》中找到。