【问题标题】:Routing, Universal apps (Nodejs, React), Error (0 , _reactRouter.match) is not a function路由,通用应用程序(Nodejs,React),错误(0,_reactRouter.match)不是函数
【发布时间】:2017-03-15 22:04:48
【问题描述】:

我无法修复此错误... 我启动服务器,一切正常,因为我刷新了 localhost:3000 然后它告诉我一个错误:

TypeError: (0 , _reactRouter.match) 不是函数

我已经安装了“react-router”:“^4.0.0”

import Express from 'express';
import {RouterContext, match} from 'react-router';
import {renderToString } from 'react-dom/server';
import React from 'react';
import routes from './routes.js'



var app = new Express();
app.set('view engine', 'ejs');
app.set('views',__dirname);


//////////////////////////////////////////////////////////////////////
app.get('*', (req, res) => {
    match(
        { routes, location: req.url },
        (err, redirectLocation, renderProps) => {

            if (err) {
                return res.status(500).send(err.message);
            }

            if (redirectLocation) {
                return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
            }

            var markup;
            if (renderProps) {
                // if the current route matched we have renderProps
                markup = renderToString(<RouterContext {...renderProps}/>);
            } else {
                // otherwise we can render a 404 page
                markup = renderToString(<NotFoundPage/>);
                res.status(404);
            }

            // render the index template with the embedded React markup
            return res.render('index', { markup });
        }
    );
});
//////////////////////////////////////////////////////////////////////////////////


var port = process.env.PORT || 3000;
app.listen(port, ()=>{
    console.log('Server is listening on port ' + port );
});

【问题讨论】:

    标签: javascript reactjs react-router isomorphic-javascript


    【解决方案1】:

    如果您在 v4 之前使用 react-router,您的代码看起来是正确的,但是 react-router v4 对整个代码库进行了重大更改,包括服务器渲染的方法。在 v4 中,有一个专门用于服务器渲染的新组件 - StaticRouter

    查看此处的服务器渲染文档: https://reacttraining.com/react-router/web/guides/server-rendering

    如果您仍然想使用 match 功能,您可以使用低于版本 4 的 react-router 版本。看看我在 very similar question from yesterday 上的回答,您可能正在使用与其他 OP 相同的样板/示例。

    【讨论】:

    • 它告诉我一个错误 StaticRouter is not defined,尽管我已经导入了一个安装的 react-router-dom 但我按照这里(scotch.io/tutorials/…)的描述做了,它只在服务器端有效。在客户端,当我打开网页时,它只显示原始文件和字典。我的代码和 scotch 代码之间的主要区别在于 webpack.config.js 文件。就是这样,为什么我的代码不能正常工作?
    猜你喜欢
    • 2023-01-26
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多