【问题标题】:React + Sails : Handling RoutesReact + Sails:处理路线
【发布时间】:2016-01-20 02:14:24
【问题描述】:

我正在使用 Sails 和 React 开发一个 Web 应用程序。我使用sails 的主要目的是利用MVC 模式,而React 用于服务视图。因为,Sails 提供了它自己的路由,但我想改用我的 React-router。

例如:在 react-router 中我们有 NotFoundRoute,所以当我访问一个不存在的页面时,它应该显示我为 NotFoundRoute 定义的处理程序。相反,它向我展示了sails 404 页面。

那么当我想使用我的 React 路线时,如何控制风帆路线?

反应路线

var JSX = require('babel/register'),
    React = require('react'),
    Router = require('react-router'),
    DefaultRoute = Router.DefaultRoute,
    NotFoundRoute = Router.NotFoundRoute,
    Route = Router.Route;


var routes = (
        <Route name="splash" path="/" handler={require('../main')}>
            <DefaultRoute handler={require('../components/Signup/signup')} />   
            <Route name="signup" path="/user/signup" handler={require('../components/Signup/signup')} />    
            <Route name="home" path="/user/home/:id" handler={require('../components/Home/home')} />
            <NotFoundRoute handler={require('../components/commons/notFound')} />
        </Route>
    );

module.exports = routes;

航行路线

module.exports.routes = {


  '/': {
    view: 'homepage'
  },

  '/user/home/:id' : 'UserController.home'


};

我对这个框架完全陌生,无法在网上找到足够的资源。很抱歉这个愚蠢的问题。

【问题讨论】:

  • 显示您的 Sails 路由器代码。可能的问题是您没有告诉 Sails 为您的 React 应用程序的 index.html 提供所有(通配符)请求。
  • @elithrar 正如你所问,我已经添加了我的航行路线。请让我知道..我需要做什么修改。
  • 查看sailsjs.org/documentation/concepts/routes/custom-routes - 使用通配符路由 - /* - 之后 你的UserController 路由。
  • 同构路由呢?

标签: reactjs sails.js


【解决方案1】:
module.exports.routes = {
  '/': {
    view: 'homepage'
  },
  '/user/home/:id' : 'UserController.home'
  '/*' : 'ReactApp.home'
};

您需要创建一个 通配符 路由,以便在缺少 api 路由时呈现 react 应用程序。 http://sailsjs.org/documentation/concepts/routes/custom-routes

【讨论】:

    【解决方案2】:

    灵感来自https://stackoverflow.com/a/21951751/2377491

    1. 使用sails new mySailsApp 创建一个新的Sails 应用
    2. 清除 mySailsApp/assets 文件夹的内容
    3. 将 myReactApp/dist 文件夹的内容复制到 mySailsApp/assets 中
    4. 将 mySailsapp/views/layout.ejs 的内容替换为 myReactApp/dist/index.html 文件的内容
    5. 从layout.ejs文件中剪切所有非脚本标签内容(&lt;body&gt;标签之后和第一个&lt;script&gt;标签之前的所有内容,并用它来替换mySailsApp/views/homepage.ejs的内容
    6. 在 layout.ejs 中将 &lt;%-body%&gt; 放在 &lt;body&gt; 标记之后

    在你的 config/routes.js 中,输入:

    module.exports.routes = {
      '/*': {
        view: 'homepage',
        skipAssets: true
      }
    }
    

    然后您可以使用sails lift 启动服务器,您将在http://localhost:1337 看到React 应用程序。

    【讨论】:

    • 如果您的 API 已有其他路由,则必须在新路由中添加此属性:skipRegex: /^\/api\/.*$/
    【解决方案3】:

    虽然这是一个较老的问题,但近 5 年后它仍然具有相关性。

    我最近开源了Sails/React/Bootstrap/Webpack 的基本配置,这对可能偶然发现这个问题的任何人都有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2012-03-07
      • 1970-01-01
      • 2019-06-30
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多