react redux 服务端渲染 server如何根据不同路由dispatch不懂的action
match({routes: routes(store.getState()), location: req.url}, (err, redirectLocation, renderProps) => {
if (err) {
res.status(500).end(`Internal Server Error ${err}`);
} else if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
Promise.all([
// loginManage()
store.dispatch(fetchGetCitys())
])
.then(() => {
console.info('zzzzzzzzzzzzzzz',store.getState())
const html = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
);
//res.end(renderFullPage(html, store.getState()));
res.render('index', {
__html__: html,
__state__: JSON.stringify(store.getState())
})
});
} else {
res.status(404).end('Not found');
}
});
//在响应客户端之前 我dispatch了fetchGetCitys这个action 但是如何根据不同的路由dispatch不同的action呢?
需要在组件上定义一个方法用于在服务端渲染时调用获取数据:
match 的回调函数中有一个 renderProps,renderProps.components 可以得到当前 router 的所有组件。
大概就是这样。