【问题标题】:react-redux-router doesn't workreact-redux-router 不起作用
【发布时间】:2016-02-22 14:53:18
【问题描述】:

我是 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
);

而且我有 Home 组件使用的 Navigation 组件。

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>
    );
  }
}

当我点击链接时...什么也没有发生。为什么?

【问题讨论】:

    标签: reactjs react-router redux


    【解决方案1】:

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

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

    当您访问 foo 链接时,它正在匹配该部分并加载 Home 组件。它还匹配 URL 中的“foo”,因此它尝试将 RegisterPage 组件添加为 Home 中的 children 属性,但该组件不会在任何地方呈现 this.props.children。这就是没有渲染 RegisterPage 的原因。

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 1970-01-01
      • 2017-10-23
      • 2017-10-09
      • 2018-07-31
      • 2017-09-07
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      相关资源
      最近更新 更多