0
我有一個反應應用程序,我試圖根據從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
?