【发布时间】:2017-05-25 01:33:31
【问题描述】:
我有一个反应应用程序,我试图根据从 redis 缓存调用的数据生成路由。
我正在使用https://github.com/ayroblu/ssr-create-react-app-v2
我有一个路由组件,它循环通过 this.props.pages 并像这样创建路由:
class Routes extends Component {
getRoutes(){
let container = null;
const routes = []
/**
* We use a switch statement because the Routes component
* attribute wont take a string so we need to call
* the object that we import i.e. HomePage
*/
forEach(this.props.pages, page => {
switch(page.template){
case 'home':
container = HomePage
break;
case 'about':
container = AboutPage
break;
default:
throw new Error("No page container matching page's template")
return;
}
routes.push(<Route path={`${page.path}`} component={container} key={key}/>)
})
return routes;
}
render() {
return (
<Switch>
{this.getRoutes()}
<Route component={NoMatch}/>
}
</Switch>
)
}
}
我有一个页面缩减器,它从 redis 缓存中异步获取路由的页面数据,如下所示:
import { SET, RESET } from '../types/page'
import getInitialState from './../../server/initialState'
async function getInitialStateFromCache() {
const initialState = await getInitialState();
const {pages} = initialState[0]
return pages
}
const initialState = getInitialStateFromCache()
export default function reducer(state=initialState, action) {
switch (action.type) {
case SET:
return Object.assign({}, state, action.payload)
case RESET:
return {...initialState}
default:
return state
}
}
当在我的路由组件中调用第一个渲染时,this.props.pages 未定义,因此请求的页面 404 是客户端中的第二个渲染,它会出现。这意味着当我查看页面源时,内容还没有被服务器端渲染。
如何延迟第一次渲染,以便在需要时定义 this.props.pages?
【问题讨论】:
标签: javascript node.js reactjs redux react-redux