基于React-Route渲染React组件

时间:2017-12-16 02:07:46

标签: reactjs react-router-v4

我正在尝试根据 React React-Router v4 Redux 在我的主要部分内呈现另一个组件内的特定组件'面板'包装在固定的标题和侧边栏组件中。

例如,当我从侧边栏中选择一个项目时,我会渲染Detail面板并根据ID加载详细信息,例如:<Route path='/item/:id' component={ItemDetail} />

Outline navigating React-Router

routes.js

  import React, { Component } from 'react';
    import { RouteHandler, Switch, Route, DefaultRoute } from 'react-router';
    import App from './containers/App';
    import Login from './containers/Login';
    import LobbyDetail from './components/LobbyDetail';
    export default (
      <Switch>
        <Route exact path="/" component={App} />
        <Route exact path="/login" component={Login} />
      </Switch>
    );

app.js:

import React, { Component } from 'react'
import { Router, Route, Link } from 'react-router'
import { connect } from 'react-redux'
import PropTypes from 'prop-types';
import auth from '../actions/auth';
import Sidebar from '../Components/Sidebar'

class App extends Component {
    static propTypes = {
    };

    /**
     * 
     */
    render() {
        const { ... } = this.props
        return (
            <div className="container-fluid">
                <div className="row">
                    {* I WANT TO RENDER DYNAMIC COMPONENT HERE *}
                </div>
                <Sidebar currentUser={currentUser}
                    logout={logout}
                    />
            </div>
        );
    }
}

// ...

export default connect(mapStateToProps, mapDispatchToProps)(App)

index.js(基本上是主应用):

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createMemoryHistory } from 'history';
import routes from './routes';
import configureStore from './store/store.js';
import { AppContainer } from 'react-hot-loader';

const syncHistoryWithStore = (store, history) => {
  const { routing } = store.getState();
  if (routing && routing.location) {
    history.replace(routing.location);
  }
};

const initialState = {};
const routerHistory = createMemoryHistory();
const store = configureStore(initialState, routerHistory);
syncHistoryWithStore(store, routerHistory);

const rootElement = document.querySelector(document.currentScript.getAttribute('data-container'));

const render = () => {

  ReactDOM.render(
    <AppContainer>
      <Provider store={store}>
        <ConnectedRouter history={routerHistory}>
          {routes}
        </ConnectedRouter>
      </Provider>
    </AppContainer>,
    rootElement
  );
}

render();

if (module.hot) { module.hot.accept(render); }

1 个答案:

答案 0 :(得分:2)

您正在寻找的是参数化路由。像<Route/>一样<Route path='/item/:id' component={ MyComponent } />MyComponent

现在在props.match.params.id中,您可以使用:id的值来有条件地呈现,或者如果您尝试根据componentWillReceiveProps的值加载异步数据;您可以使用this.props.match.params.id生命周期方法,并根据<Link to='/item/some-item'/>的值发送操作。

注意:match.params.id会将'some-item'的值设置为login_required