【问题标题】:All React Router and hashHistory routes redirect to same component所有 React Router 和 hashHistory 路由都重定向到同一个组件
【发布时间】:2017-09-27 18:30:04
【问题描述】:

我试图在我的 MERN 堆栈应用程序上使用 React Router 时遇到了问题,因为所有路由都在渲染相同的组件

路由器(index.jsx):

import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import Home from './components/home.jsx'
import App from './app.jsx'
import ContactsIndex from './components/contacts/contactsIndex.jsx'

if(typeof window !== 'undefined') {
    ReactDOM.render(
    <Router history={hashHistory}>
        <Route path='/' component={App}>
          <IndexRoute component={Home} />
          <Route path='contacts' component={ContactsIndex}/>
        </Route>
    </Router>, document.getElementById("root"));
}

App.jsx

import React from 'react'
import { Router, Route, Link } from 'react-router'
import Home from './components/home.jsx'

export default class App extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return(
      <div>
        <p>Text</p>
        {this.props.children}
      </div>
    )
  }
}

从 express 进入 React:

app.set('views', __dirname + '/views');
app.engine('jsx', require('express-react-views').createEngine())
app.set('view engine', 'jsx')

app.get('*', (req,res) => {
  res.render('index.jsx')
})

无论我访问什么路线(即使是未定义的路线),都会呈现 App.jsx 的内容。似乎我在这里做错了事情,这使得 hashHistory 不起作用。我正在使用 React-Router 2.6.1

【问题讨论】:

    标签: node.js reactjs express react-router


    【解决方案1】:

    如果您查看您的代码,您可以看到您的路由器首先安装了应用程序组件,对吧

    <Router history={hashHistory}>
        <Route path='/' component={App}>
    ...
    

    然后你的 App 组件中有这个:

    {this.props.children}
    

    因此,React 路由器的工作方式是使用 App.js 作为容器,您在其中安装其他组件。

    例如,如果您转到 /contacts,您的树将如下所示

    <div>  //This is the app component
        <p>Text</p>
        <ContactsIndex> // Whatever route you render goes here...
    </div>
    

    如果您只想在每个路由上呈现一个新树,那么使用当前的实现,您可以将 App.js div 保留为您的页面的包装器。

    【讨论】:

    • 这是有道理的。但是,问题在于,在每条路线上,只有 app.jsx 的内容被渲染,而没有其他组件被渲染。似乎 this.props.children 是未定义的,因此没有孩子被渲染。我一定是错误地传递了它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2017-09-01
    • 2021-07-24
    • 1970-01-01
    • 2015-09-30
    • 2016-01-14
    相关资源
    最近更新 更多