react-redux-router不起作用

时间:2016-02-22 14:53:19

标签: reactjs react-router redux

我是Redux的新手。现在我正在尝试使用redux-react-router,但我遇到了问题。我点击了链接,没有任何反应。我的应用程序不呈现组件,也不会更改URL。

我的app.js文件包含以下代码:

import '../stylesheets/main.scss';

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { combineReducers, createStore } from 'redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { routerReducer } from 'react-router-redux';
import rootReducer from './reducers/rootReducer';

import Home from './containers/HomePage';
import RegisterPage from './containers/RegisterPage';

import 'lazysizes';

const store = createStore(
  combineReducers({
    rootReducer,
    routing: routerReducer
  })
);

const rootElement = document.getElementById('root');

render(
  <Provider store={store}>
     <Router history={browserHistory}>
      <Route path="/" component={Home}>
        <IndexRoute component={Home} />
        <Route path="foo" component={RegisterPage}/>
      </Route>
    </Router>
  </Provider>,
  rootElement
);

我有 主页 组件使用的 导航 组件。

import React, { Component } from 'react';

import classNames from 'classnames';
import { Link } from 'react-router';

export default class Navigation extends Component {

  constructor() {
    super();

    this.state = {
      links: [
        { href: '#', isActive: true, title: 'Home' },
        { href: '/foo', isActive: false, title: 'Lorem' }
      ]
    };
  }

  render() {
    return (
      <nav className="navigation" role="navigation">
        <ul className="navigation_list" role="list">
          {this.state.links.map((link, i) => {
            const linkClass = classNames({
              link: true,
              'link-active': link.isActive
            });

            return (
              <li key={i} className="item" role="listitem">
                <Link className={linkClass} to={link.href}>{link.title}</Link>
              </li>
            );
          })}
        </ul>
      </nav>
    );
  }
}

当我点击链接时......没有任何反应。为什么呢?

1 个答案:

答案 0 :(得分:2)

您的路线定义不正确。试试这个:

<Router history={browserHistory}>
  <Route path="/"> <!-- No component on this line -->
    <IndexRoute component={Home} />
    <Route path="foo" component={RegisterPage}/>
  </Route>
</Router>

当您访问foo链接时,它与部件匹配并加载Home组件。它还匹配URL中的“foo”,因此它尝试在Home中添加RegisterPage组件作为children道具,但该组件不会在任何位置呈现this.props.children。这就是RegisterPage没有被渲染的原因。