javascript 从 Express 调用 React View

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29635162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:48:04  来源:igfitidea点击:

Calling React View from Express

javascriptnode.jsreactjsreact-jsx

提问by PositiveGuy

I can't find a good bare minimum example where I can wire up an express.js route to call a react view.

我找不到一个很好的最低限度的例子,我可以在其中连接 express.js 路由来调用反应视图。

So far this is what I have.

到目前为止,这就是我所拥有的。

+-- app.js
+-- config
|   +-- server.js
+-- routes
|   +-- index.js
+-- views
|   +-- index.html

app.js

应用程序.js

require('./config/server.js');
require('./routes/index.js');

config | server.js

配置| 服务器.js

"use strict";
var express = require('express'),
app = express(),

routes = require('./routes');

app.set('view engine', 'html');
app.engine('html', ); // how do I tell express that JSX is my template view engine?

var port = process.env.PORT || 3000;

app.engine('handlebars', exphbs({ defaultLayout: 'main'}));
app.set('view engine', 'handlebars');


var server = app.listen(port, function(){
    console.log('Accepting connections on port ' + port + '...');
});

routes | index.js

路线 | 索引.js

app.get('/', function(request, response){
    // how do we call the route that will run index.html ?
    request.render('index');
});

views | index.html

意见 | 索引.html

<!DOCTYPE html>
<html>
<head>
    <script src="build/react.js"></script>
    <script src="build/JSXTransformer.js"></script>
    <script type="text/jsx" src="build/noEpisodes.js"></script>
</head>
<body>
    <div id="noEpisodesMessage"></div>
</body>
</html>

and then my index.htm page as well as generated jsx.

然后是我的 index.htm 页面以及生成的 jsx。

回答by Mike 'Pomax' Kamermans

The usual thing is to use react-routerto take care of the routes, write your React app as a single React app (i.e. all your JSX source ends up bundles into a single app.js file, which knows how to load all your "pages" or "views") and then use express (or Hapi, or any other server process) mostly as your API and asset server, not your page/view generator.

通常的做法是使用react-router来处理路由,将你的 React 应用程序编写为一个单一的 React 应用程序(即你所有的 JSX 源最终都打包成一个 app.js 文件,它知道如何加载你所有的“页面”或“视图”),然后主要使用 express(或 Hapi,或任何其他服务器进程)作为您的 API 和资产服务器,而不是您的页面/视图生成器。

You can then tap into the routes you set up in the react-routerRouter object so that on the express side you can forward your users to the URL that react-routercan deal with for content loading, so you get

然后,您可以利用您在react-routerRouter 对象中设置的路由,以便在 Express 方面将您的用户转发到react-router可以处理内容加载的 URL ,这样您就可以得到

  1. user request site.com/lol/monkeys
  2. express redirects to /#/lol/monkeys
  3. your react app loads the correct view because of the routes in Router
  4. optionally, your app does a history.replaceState so that the user sees site.com/lol/monkeys (there are some react-router tricks to do this for you)
  1. 用户请求 site.com/lol/monkeys
  2. 快速重定向到 /#/lol/monkeys
  3. 由于路由器中的路由,您的反应应用程序加载了正确的视图
  4. 可选地,您的应用程序执行 history.replaceState 以便用户看到 site.com/lol/monkeys(有一些 react-router 技巧可以为您执行此操作)

You can also automate most of this through server-side-rendering but the name can be confusing: you stillwrite your React app as if there is no server involved at all, and then rely on React's render mechanism to fully render individual "pages" for a requested URL which will show all the right initial content while alsothen loading your app and silently hooking it back into the content the user is looking at, so that any interactions past the initial page load are handled by React again, and subsequent navigation is "fake" navigation (your url bar will show a new URL but no actual network navigation will happen, React simply swaps content in/out).

您还可以通过服务器端渲染来自动化大部分工作,但名称可能会令人困惑:您仍然编写 React 应用程序,就好像根本不涉及服务器一样,然后依靠 React 的渲染机制来完全渲染各个“页面”对于请求的 URL,它将显示所有正确的初始内容,同时加载您的应用程序并静默地将其挂接到用户正在查看的内容中,以便在初始页面加载之后的任何交互都由 React 再次处理,以及随后的导航是“假”导航(你的 url 栏会显示一个新的 URL,但不会发生实际的网络导航,React 只是交换内容输入/输出)。

A good example for this is https://github.com/mhart/react-server-example

一个很好的例子是https://github.com/mhart/react-server-example

回答by ChetPrickles

The other answers work with the usual way to use react, to replace an element in the dom like so

其他答案与使用反应的常用方法一起工作,像这样替换 dom 中的元素

React.render(<APP />, document);

but if you want react to be your "template language" in express, you can also use react to render a simple string of html like so

但是如果你想让 react 成为你的“模板语言”,你也可以使用 react 来渲染一个简单的 html 字符串,就像这样

app.get('/', function(req, res) {
  var markup = React.renderToString(<APP />);  // <-- render the APP here
  res.send(markup);                          // <-- response with the component
});

there are a few other things you need to take care of in terms of bundling all the dependencies and working with jsx. this simple minimalist tutorialand this blog posthelped me understand the situation better

在捆绑所有依赖项和使用 jsx 方面,您还需要注意其他一些事情。这个简单的极简教程和这篇博文帮助我更好地了解了情况

note that the sample code in the tutorial uses this syntax

请注意,教程中的示例代码使用此语法

var markup = React.renderToString(APP());

which has been deprecated and will cause an error. to use it you'd have to replace

这已被弃用并会导致错误。要使用它,您必须更换

var APP = require('./app');

with

var APP = React.createFactory(require('./app'));

or just render jsx like i did in the first example. to get the tutorial to work i might have also had to use more recent versions of the dependencies in package.json.

或者像我在第一个示例中所做的那样渲染 jsx。为了让教程工作,我可能还必须在 package.json 中使用更新版本的依赖项。

once you've got that down a fancier tutorialshows a more powerful way to use react-engine to render react within express

一旦你明白了,一个更高级的教程展示了一种更强大的方法来使用 react-engine 在 express 中渲染 react

回答by deowk

If you want to keep it simple you can do this for the entry point of your app:

如果您想保持简单,您可以在应用程序的入口点执行此操作:

routes | index.js

路线 | 索引.js

app.get('/', function(request, response){

    // how do we call the route that will run index.html ?
    res.sendfile('../views/index.html');
});

React is going to target a specific element on your index.html page in it's render method:

React 将在它的 render 方法中定位 index.html 页面上的特定元素:

React.render(<Application />, document.getElementById('foo')); 

So if your javascript is included in index.html and an element with that id is present react is going to inject your Application into that div. From that point onwards you can do all of the routing with react-router OR you can setup different routes in express and handle them like you did index.html

因此,如果您的 javascript 包含在 index.html 中并且存在具有该 id 的元素,则 react 会将您的应用程序注入该 div。从那时起,您可以使用 react-router 完成所有路由,或者您可以在 express 中设置不同的路由并像处理 index.html 一样处理它们

回答by Tyler

Instead of manually dealing with React.render you can use a library called react-helper (https://github.com/tswayne/react-helper). It sets up a div for you, binds your react components to the div, allows you to pass properties to your components server side, and can even handle server-side rendering if you have webpack configured for your node app or are willing to use babel-register (not recommended for prod).

您可以使用名为 react-helper ( https://github.com/tswayne/react-helper)的库,而不是手动处理 React.render 。它为你设置一个 div,将你的 react 组件绑定到 div,允许你将属性传递给你的组件服务器端,如果你为你的 node 应用程序配置了 webpack 或者愿意使用 babel,它甚至可以处理服务器端渲染-注册(不推荐用于产品)。