freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/react/render-react-on-the-server-...

77 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
id: 5a24c314108439a4d403618d
title: Render React on the Server with renderToString
challengeType: 6
isRequired: false
videoUrl: ''
localeTitle: 使用renderToString在服务器上渲染React
---
## Description
<section id="description">到目前为止您已在客户端上呈现React组件。通常这是你将永远做的。但是在某些用例中在服务器上呈现React组件是有意义的。由于React是一个JavaScript视图库您可以使用Node在服务器上运行JavaScript这是可能的。实际上React提供了一个<code>renderToString()</code>方法您可以将其用于此目的。有两个关键原因可以解释为什么服务器上的渲染可能会在真实世界的应用程序中使用。首先如果不这样做你的React应用程序将包含一个相对空的HTML文件和一大堆JavaScript当它最初加载到浏览器时。对于试图索引页面内容以便人们可以找到您的搜索引擎而言这可能并不理想。如果在服务器上呈现初始HTML标记并将其发送到客户端则初始页面加载包含搜索引擎可以抓取的所有页面标记。其次这会创建更快的初始页面加载体验因为呈现的HTML小于整个应用程序的JavaScript代码。 React仍然能够识别您的应用并在初始加载后进行管理。 </section>
## Instructions
<section id="instructions"> <code>renderToString()</code>方法在<code>ReactDOMServer</code>上提供在此处可用作全局对象。该方法采用一个参数它是一个React元素。使用此选项将<code>App</code>呈现为字符串。 </section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>App</code>组件应使用<code>ReactDOMServer.renderToString</code>呈现为字符串。
testString: 'getUserInput => assert(getUserInput("index").replace(/ /g,"").includes("ReactDOMServer.renderToString(<App/>)") && Enzyme.mount(React.createElement(App)).children().name() === "div", "The <code>App</code> component should render to a string using <code>ReactDOMServer.renderToString</code>.");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='jsx-seed'>
```jsx
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div/>
}
};
// change code below this line
```
</div>
### Before Test
<div id='jsx-setup'>
```jsx
var ReactDOMServer = { renderToString(x) { return null; } };
```
</div>
### After Test
<div id='jsx-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>