react服務端渲染(八)路由改寫

  1. 每個用戶使用不一樣的store
  2. 請求發送axios/fetch,選擇使用fetch進行異步請求的發送 在瀏覽器端能夠直接使用fetch發送,無需安裝。可是服務端會報error:fetch is not defined,由於fetch()是爲瀏覽器設計的,而後在第三方模塊中後端移植到node.js,因此須要安裝node-fetch;
    import fetch from 'node-fetch'
  3. 定義常量保存字符串 避免錯誤難以發現
  4. componentDidMount只會在客戶端執行 服務端不執行,解決辦法:給每個組件寫一個靜態方法(例如:getData),服務端經過匹配path參數,拿到每一個組件對應的方法執行https://www.npmjs.com/package/react-router-config
    1. 給組件寫一個靜態方法
      const Home = () => {
          useEffect(() => {
              Home.getData()
          })
      
          return(
              <div></div>
          )
      }
      //靜態方法
      Home.getData = () => {
           // console.log(123);
      }
    2. 改寫咱們的路由,不寫path就匹配全部的路徑
      export default [
          {
              path: '/',
              exact: true,
              getData: Home.getData,
              component: Home,
          },{
              path: '/Login',
              getData: ()=>{console.log('getData login')},
              component: Login
          }
      ]
  5. 結合用戶請求的路徑判斷異步請求的接口,react-router-config複雜路由配置:matchRoutes 多級路由匹配
    //匹配咱們的路由
    const mathPath = matchRoutes(Routers,req.path);
    //遍歷匹配到的路由 執行對應的方法 因爲方法是異步的使用promise.all來在全部方法執行完畢以後 再渲染store
    mathPath.map(path=>{ path.route.getData? promiseAll.push(path.route.getData(Store.dispatch)):'' })
    Promise.all(promiseAll).then(()=> {
      //執行html字符串的生成  
    })

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

相關文章
相關標籤/搜索