2017-10-11 57 views
0

我确实发现我在服务器上呈现我的应用时无法使用。我想根据情况将我的应用程序包装在指定的路由器中 - CLient端的BrowserRouter和服务器端的StaticRouter。我的应用程序是这样的:服务器上的react-router-dom

imports...... 
class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
    } 
    } 

    render() { 
     return (
     <BrowserRouter> 
      <div> 
      <Menu /> 
      <main> 
       <Switch> 
       <Route exact path="/about" component = {About} /> 
       <Route exact path="/admin" component = {BooksForm} /> 
       <Route exact path="/cart" component = {Cart} /> 
       <Route exact path="/" component = {BookList} /> 
       </Switch> 
       <Footer /> 
      </main> 
      </div> 
     </BrowserRouter> 
    ); 

    } 

    componentDidMount(){ 
    this.props.getCart(); 
    } 
} 

function mapDispatchToProps(dispatch) { 
    return bindActionCreators({ 
    getCart 
    }, dispatch) 
} 

export default connect(null, mapDispatchToProps)(App); 

我试图移动此组件的我BrowserRouter OU所以我index.js看起来像这样:

imports.... 
const renderApp =() => (
    <Provider store={createStoreWithMiddleware(reducers)}> 
    <BrowserRouter> 
     <App/> 
    </BrowserRouter> 
    </Provider> 
) 

const root = document.getElementById('app') 
render(renderApp(), root) 

所以我会去总结我的应用程序的能力不同的路由器问题是,当我将BrowserRouter移出App应用程序组件时,它停止工作。点击链接不起作用了。网址正在改变,但我的应用程序不渲染不同的组件。如何将路由器移出此组件?

+0

你也可以两个路由器之间通过动态地设置组件标签切换: '常量RouterComponent = isClient? BrowserRouter:StaticRouter;' then''' –

回答

0

在服务器上,你会包装你的应用程序与此类似:

const routerContext = {}; 

const appComponent = (
    <Provider store={store}> 
     <StaticRouter location={req.url} context={routerContext}> 
     <App /> 
     </StaticRouter> 
    </Provider> 
); 

当你通过反应路由器的位置(从URL)以及上下文对象。

的客户端是喜欢你的例子:

<Provider store={createStoreWithMiddleware(reducers)}> 
    <BrowserRouter> 
    <App/> 
    </BrowserRouter> 
</Provider>