这就是我所做的 - 这是我从文档中提出的。
routes.cfg.js
首次设置路由的配置中,可以使用客户端应用,并出口到服务器上使用过的方式。
export const getRoutesConfig =() => [
{
name: 'homepage',
exact: true,
path: '/',
component: Dasboard
},
{
name: 'game',
path: '/game/',
component: Game
}
];
...
// loop through config to create <Routes>
服务器
设置服务器的路由消耗以上的配置,并检查有一个名为needs
属性的组件(这个你喜欢什么,也许ssrData
或其他)。
// function to setup getting data based on routes + url being hit
async function getRouteData(routesArray, url, dispatch) {
const needs = [];
routesArray
.filter((route) => route.component.needs)
.forEach((route) => {
const match = matchPath(url, { path: route.path, exact: true, strict: false });
if (match) {
route.component.needs.forEach((need) => {
const result = need(match.params);
needs.push(dispatch(result));
});
}
});
return Promise.all(needs);
}
....
// call above function from within server using req/ctx object
const store = configureStore();
const routesArray = getRoutesConfig();
await getRouteData(routesArray, ctx.request.url, store.dispatch);
const initialState = store.getState();
container.js/component.jsx
设置数据取为组件。确保您将needs
数组添加为属性。
import { connect } from 'react-redux';
import Dashboard from '../../components/Dashboard/Dashboard';
import { fetchCreditReport } from '../../actions';
function mapStateToProps(state) {
return { ...state.creditReport };
}
const WrappedComponent = connect(
mapStateToProps,
{ fetchCreditReport }
)(Dashboard);
WrappedComponent.needs = [fetchCreditReport];
export default WrappedComponent;
只需注意,此方法适用于挂钩到匹配路径而不是嵌套组件的组件。但对我来说这一直很好。在路由级别的组件执行数据提取,然后稍后需要它的组件将其传递给它们,或者添加一个连接器以从商店直接获取数据。