react服務端渲染(九)proxy代理&&多級路由&&數據的脫水和注水

 項目地址:git@github.com:longlongdan/Reactssr.gitnode

  1. 服務端渲染以後,客戶端會再次渲染,由於咱們的客戶端建立的store爲空。解決辦法:在服務端渲染的時候將獲取到的數據賦值一個全局變量(注水),客戶端建立的store以這個變量的值做爲初始值(脫水)。
    const Store = createStore(Rducer,window.info,applyMiddleware(thunk));
  2. 中間層代理轉發,咱們的瀏覽器端渲染以前是直接發送'http://47.95.113.63/ssr/api/news.json?secret=PP87ANTIPIRATE'遠程服務器上取數據,如今咱們須要,讓他請求咱們本地的node服務器,node服務器去代理這個請求帶遠程服務器上面,
    //瀏覽器端發送代碼 至關於請求的是localhost:3000/api/news...
    return fetch('/api/news.json?secret=PP87ANTIPIRATE')
         .then((res)=>{
             return res.json();
         })
    //後端proxy代理
    const proxy = require('http-proxy-middleware');
    app.use('/api',proxy({
        target: 'http://47.95.113.63/ssr'
    }))
    使用代理以後服務端異常,由於咱們服務端請求至關因而 :服務端根路徑+/api/news.json?secret=PP87ANTIPIRATE;因此咱們須要對服務端和瀏覽器端採用不一樣的請求路徑

  3. (瞭解axios中instanse的寫法 interceptors 概念)咱們使用的fetch,能夠本身對fetch方法進行封裝
    //客戶端
    const baseUrl = '';
    const  fetchClient = (url) => {
        return fetch(baseUrl+url);
    }
    export default fetchClient;
    //服務端
    import fetch from 'node-fetch'
    
    const baseUrl = 'http://47.95.113.63/ssr';
    const fetchServer = (url) => {
        return fetch(baseUrl+url);
    }
    export default  fetchServer;
  4. thunk的withExtraArgument的用法,爲咱們中間件調用的時候傳入額外的參數。fetch方法封裝好以後咱們須要判斷代碼執行在瀏覽器端仍是服務端,解決辦法是經過thunk中間件在建立store的時候將封裝的fetch方法傳進來。
    //客戶端
    const Store = createStore(Rducer,window.info,applyMiddleware(thunk.withExtraArgument(fetchClient))); 
    
    //服務端
    const Store = createStore(Reducer, applyMiddleware(thunk.withExtraArgument(fetchServer)));

    發送請求的代碼,會接受第三個參數,就是咱們自定義的額外參數ios

    export const getHomeList = (dispatch, getState, fetch) => {
        return fetch('/api/news.json?secret=PP87ANTIPIRATE')
         .then((res)=>{
             return res.json();
         })
    }
  5. rnderRoutes對多級路由的區別 renderRoutes方法會去幫咱們渲染一級路由,而後將下一層的routes(二級路由)帶進一級路由所匹配到的組件之中,咱們須要在一級路由匹配的組件裏面再次調用renderRoutes方法對props.route.routes進行渲染
    //router.js
    export default [
        {
            path: '/',
            component: Header, //共用的header頭部
            routes: [
                {
                    path: '/',
                    exact: true,
                    getData: Home.getData,
                    component: Home,
                },
                {
                    path: '/Login',
                    getData: ()=>{console.log('getData login')},
                    component: Login
                }
            ]
        }
    ]

    在header裏面須要繼續渲染二級路由git

    const Header = (props) => {
        return (
            <div>
                <Link to='/'>Home</Link>
                <br/>
                <Link to='/Login'>Login</Link>
                { renderRoutes(props.route.routes) }
            </div>
        )
    }
相關文章
相關標籤/搜索