2017-07-03 121 views
2

这是例如,从官方文档(https://reacttraining.com/react-router/web/guides/server-rendering/data-loading):如何使用react-router v4预加载数据?

import { matchPath } from 'react-router-dom' 

// inside a request 
const promises = [] 
// use `some` to imitate `<Switch>` behavior of selecting only 
// the first to match 
routes.some(route => { 
    // use `matchPath` here 
    const match = matchPath(req.url, route) 
    if (match) 
    promises.push(route.loadData(match)) 
    return match 
}) 

Promise.all(promises).then(data => { 
    // do something w/ the data so the client 
    // can access it then render the app 
}) 

本文档让我很紧张。此代码不起作用。这个问题不起作用!我如何预先加载服务器中的数据?

回答

0

这就是我所做的 - 这是我从文档中提出的。

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; 

只需注意,此方法适用于挂钩到匹配路径而不是嵌套组件的组件。但对我来说这一直很好。在路由级别的组件执行数据提取,然后稍后需要它的组件将其传递给它们,或者添加一个连接器以从商店直接获取数据。