反应& HashRouter - 得到空白页面

时间:2017-08-22 08:07:40

标签: javascript reactjs routing react-router

在我react-router-dom设置客户端路由后,我只得到了空白页。

https://www.w3schools.com/bootstrap/bootstrap_scrollspy.asp

所以,我的设置就在这里。我打赌有些事情是错的,但我无法得到它。

那怎么来的?怎么了?

指数:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import {
    HashRouter as Router,
    Route,
    Link
} from 'react-router-dom'

import App from './containers/app.js';
import configureStore from './store/configureStore';
import routes from './routes';

const store = configureStore();

ReactDOM.render(
    <Provider store={store}>
        <Router routes={routes} />
    </Provider>,
    document.getElementById("content")
);

路线在这里:

import React from 'react';
import ReactDOM from 'react-dom';
import {
    HashRouter as Router,
    Route,
    Link
} from 'react-router-dom';

import App from './containers/app.js';
import Settings from './components/settings/settings.js';
import NotFound from './components/common/notfound';

export default (
    <Route exact path="/" component={App}>
        <Route exact path="/settings" component={Settings} />
        <Route path="*" component={NotFound} />
    </Route>
)

1 个答案:

答案 0 :(得分:3)

尝试将此部分更改为:

ReactDOM.render(
    <Provider store={store}>
    <Router>
      <Route exact path="/" component={App}>
        <Route exact path="/settings" component={Settings} />
        <Route path="*" component={NotFound} />
      </Route>
    </Router>
    </Provider>,
    document.getElementById("content")
);

我不认为react-router v4会认出这一部分:<Router routes={routes} />

<强>修: 上述代码存在两个问题。

1)您不应在路径中放置子路径。这部分不正确:

<Route exact path="/" component={App}>
  <Route exact path="/settings" component={Settings} />
  <Route path="*" component={NotFound} />
</Route>

2)无论路径是什么,总是会呈现<NotFound />

<强>解决方案:

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import {
    HashRouter as Router,
    Route,
    Link,
} from 'react-router-dom'

import App from './containers/app.js';
import configureStore from './store/configureStore';
import routes from './routes';

const store = configureStore();

ReactDOM.render(
    <Provider store={store}>
        <Router>
          <Route path="/" component={App} />
        </Router>
    </Provider>,
    document.getElementById("content")
);

App.js

将此代码插入您要呈现内容的位置:

<Switch>
   <Route exact path="/" component={Home} />
   <Route exact path="/settings" component={Settings} />
   <Route path="*" component={NotFound} />
</Switch>

不要忘记添加import {Switch, Route} from 'react-router-dom';