React.js - React Router内容不变

时间:2016-05-09 15:37:49

标签: javascript reactjs react-router

我正在尝试设置我的react.js环境来构建UI工具包。我正在使用react-router,但由于某种原因,当我点击从Index.js呈现的链接时,URL会发生变化,但内容保持不变。它只是继续显示index.js页面中的内容,而不是更改为我单击的链接的内容。我没有在控制台上收到任何错误消息。

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';

function run(){
const reactMount = document.getElementById('app');

ReactDOM.render(<Router onUpdate={() => window.scrollTo(0, 0)} history=    {browserHistory} routes={routes}/>, reactMount );
}

new Promise((resolve) => {
if (window.addEventListener) {
  window.addEventListener('DOMContentLoaded', resolve);
} else {
  window.attachEvent('onload', resolve);
}
}).then(run)

routes.js

import React from 'react';
import { IndexRoute, Route } from 'react-router';

import Index from './pages/Index';
import Text from './pages/Text';
import Icon from './pages/Icon';

var routes = (
  <Route  path="/" component={Index}>
      <Route path="/Text" component={Text} />
      <Route path="/Icon" component={Icon} />
  </Route>
);

export default routes;

页/ Index.js

import React from 'react';
import {Link} from 'react-router';

class Index extends React.Component {
render() {

return (
  <div>
  <ul role="nav">
      <li><Link to="/Text">Text</Link></li>
      <li><Link to="/Icon">Icon</Link></li>
    </ul>
  </div>
)
}
}

export default Index;

页/ Text.js

import React from 'react';

class Text extends React.Component {
render() {
return (
  <div>
    <h1>Text</h1>
  </div>
)
}
}

export default Text;

1 个答案:

答案 0 :(得分:2)

这里有两件事:

  • 路由配置中的嵌套路线文字和图标不应位于/之前。它应该是这样的:<Route path="Text" component={Text} />
  • 在容器组件(索引)中,您需要访问this.props.children,以便组件知道呈现它的子项(嵌套路由)。

    // Index.js
    
    return (
      <div>
        <ul role="nav">
          <li><Link to="/Text">Text</Link></li>
          <li><Link to="/Icon">Icon</Link></li>
        </ul>
    
        { this.props.children }
      </div>
    )