簡體   English   中英

React和動態路由,包括文件名和擴展名

[英]React and Dynamic Routes including Filename and Extension

我是React的新手,並試圖將CMS驅動的應用程序集成為POC。 我主要停留在如何在React應用程序中將完整的URL(包括文件名和ext)放入動態路由中。 例如,如果我稱這個

http:// localhost:8080 / en / us / fly / index

動態路線將其拾取。 但是如果我叫這個

http:// localhost:8080 / en / us / fly / index.html

我收到以下錯誤。 無法獲取/en/us/fly/index.html

要求我處理所有通過URL的URL,即使它們具有文件擴展名和文件名。 我的routes.jsx如下:

import React from 'react';
import {
  Switch, Route
} from 'react-router-dom';

// Pages
import Page from "./pages/Page";

class Routes extends React.Component {
  render() {

    return (
      <Switch>
        <Route path="/:page" component={Page} />
      </Switch>
    )
  }
}

export default Routes;

我的server.js如下:

const path = require('path')
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

// get an instance of router
const router = express.Router();

// serve static assets normally
router.use(express.static(__dirname + '/dist'))

router.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})

// apply the routes to our application
app.use('/', router);

app.listen(port);
console.log('Site available on port ' + port);

如何使所有URL通過動態路由? 這有可能嗎? 我需要知道React中是否存在阻止這種情況的限制,以及它在傳統的ASP.Net MVC應用程序中將如何進行這種動態路由的工作方式。

在此方面的任何幫助或建議都將不勝感激,因為我對此一無所知,並且對React世界還沒有足夠的了解以找到解決方案。

提前致謝,

您可以在路線中使用*.* 符合以下文件擴展名

<Route path="*.*" component={YOUR_COMPONENT}/> // matches /hello.jpg and /hello.html

然后您可以訪問組件中的道具

// CMS name: sample.html
this.props.params.splat[0] // For name of prop without extension. It Will give 'sample'
this.props.params.splat[1] // For extension itself. It will give 'html'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM