我确实发现当我在服务器上渲染我的应用程序时无法使用。我想根据具体情况将我的应用程序包装在指定的路由器中 - CLient端的BrowserRouter和服务器端的StaticRouter。我的应用程序看起来像这样:
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,所以我的index.js看起来像这样:
imports....
const renderApp = () => (
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
)
const root = document.getElementById('app')
render(renderApp(), root)
所以我能够将我的应用程序包装在不同的路由器中。问题是当我将BrowserRouter移出我的App组件时它停止工作。单击链接不再起作用。网址正在发生变化,但我的应用不会渲染不同的组件。如何将路由器移出此组件?
答案 0 :(得分:0)
在服务器上,您将应用程序包装为:
const routerContext = {};
const appComponent = (
<Provider store={store}>
<StaticRouter location={req.url} context={routerContext}>
<App />
</StaticRouter>
</Provider>
);
您通过react-router传递位置(来自网址)以及上下文对象。
客户端就像你的例子:
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>