2017-10-11 55 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>