【问题标题】:React app with typescript I want to integrate SSR in my app But got error用打字稿反应应用程序我想在我的应用程序中集成 SSR 但出现错误
【发布时间】:2020-06-24 01:56:37
【问题描述】:

我正在使用 ReactDOMServer 渲染应用程序,但出现以下错误:

我已经在 react typescript 项目中设置了 express。我究竟做错了什么?请帮帮我,谢谢。

以下是相关代码:

App.tsx

import * as React from 'react';

class App extends React.Component {
  render() {
    return (
      <h1>Testing App Page</h1>
    );

  }
}

export default App

entry.js

require('ignore-styles');

require("@babel/register")({

    ignore: [ /(node_modules)/ ],
    presets: [[
      "@babel/preset-env",
      {
        "targets": {
          "esmodules": true
        }
      }
    ], '@babel/preset-react']
});

require('./index');

index.js

import express from 'express';
import serverRenderer from './middleware/renderer';

const PORT = 3000;
const path = require('path');

const app = express();
const router = express.Router();
router.use('^/$', serverRenderer);

// other static resources should just be served as they are
router.use(express.static(
    path.resolve(__dirname, '..', 'build'),
    { maxAge: '1d' },
));
app.use(router);
app.listen(PORT, (error) => {
    console.log("App port listen on ", PORT);
});

中间件/renderer.js

import React from 'react'
import ReactDOMServer from 'react-dom/server'


import App from '../../src/App';
// const App = require("../../src/App"); <= also try this but not work

const path = require("path");
const fs = require("fs");

export default (req, res, next) => {

    // point to the html file created by CRA's build tool
    const filePath = path.resolve(__dirname, '..', '..', 'build', 'index.html');

    fs.readFile(filePath, 'utf8', (err, htmlData) => {
        if (err) {
            console.error('err', err);
            return res.status(404).end()
        }

        // render the app as a string
        const html = ReactDOMServer.renderToString(React.createElement(<App />));

        // inject the rendered app into our html and send it
        return res.send(
            htmlData.replace(
                '<div id="root"></div>',
                `<div id="root">${html}</div>`
            )
        );
    });
}

【问题讨论】:

    标签: node.js reactjs typescript react-router


    【解决方案1】:

    您的问题与打字稿无关。您在middleware/renderer.js 中写道:

    const html = ReactDOMServer.renderToString(React.createElement(<App />));
    

    这是不正确的。将其更改为:

    const html = ReactDOMServer.renderToString(React.createElement(App));
    

    你可以走了。

    您应该阅读错误消息。它已经告诉你出了什么问题。还可以进一步了解 React 概念,尤其是“JSX 元素”和“JSX 组件”之间的区别。

    【讨论】:

    • 那么您没有向我们显示相关的错误消息。 “不起作用”是没有意义的,告诉我们它是如何不起作用的?
    • 我尝试了您的解决方案,但出现此错误React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. 如果我直接在 html 数据中编写 App,它可以工作,但路由不起作用。 return res.send( htmlData.replace( '&lt;div id="root"&gt;&lt;/div&gt;',
      ${App}
      `));`
    • 如果我直接写 App 就可以了。对于路由需要任何配置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2019-01-16
    • 1970-01-01
    • 2022-12-17
    • 2020-10-09
    相关资源
    最近更新 更多