如何在React Router Dom中使用嵌套路由

时间:2019-09-01 18:36:12

标签: reactjs react-router react-router-dom

我正在尝试将嵌套路由与react路由器一起使用,但不适用于我。我还尝试在主应用程序上添加嵌套路由器,但是它不起作用。

App.js

import Message from './containers/Message'
import {connect} from 'react-redux'
import {addMessage, setMessages} from './store/actions/message'

import {
    BrowserRouter as Router,
    Route
} from "react-router-dom";

class App extends Component {

    constructor(props) {
        super(props)
        WebSocketInstance.addCallbacks(
            this.props.setMessagesMethod.bind(this),
            this.props.addMessageMethod.bind(this)
        )
    }

    render() {
        return (
            <Router>
                <Route exact path='/login/' component={WrappedLoginForm} />
                <Route exact path='/' component={ChatApp} />
                {/* <Route path='/:chatID' component={Message} /> */}
            </Router>
        )
    }
}

ChatApp.js

export class ChatApp extends Component {

  componentWillMount() {
    if (!this.props.loading){
      this.props.autoLogin(this.props.history)
    }
  }

  render() {
    return (
      this.props.isAuthenticated ?
      (<div id='frame' >
        <Sidepanel />
        <div className="content">
          <div className="contact-profile">
            <img src="https://www.netfort.com/assets/user.png" alt="" />
            <p>{this.props.user.username}</p>
          </div>

          <Route path='/chat/:chatID' component={Message} />

        </div>
      </div>): null
    )
  }
}

我正在尝试匹配 http://localhost:3000/chat/1 ,但消息组件未呈现。

1 个答案:

答案 0 :(得分:1)

如果您使用exact path,则不会击中任何子路线,因为这些子路线将不符合击中父路线的条件。