Routing, Universal apps (Nodejs, React), Error (0 , _reactRouter.match) is not a function

感情迁移 提交于 2019-12-08 19:34:33

问题


I can't fix this error... I start server, everything is ok, since I refresh localhost:3000 Then it show me an error:

TypeError: (0 , _reactRouter.match) is not a function

I have installed "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 );
});

回答1:


Your code looks correct if you used react router prior to v4, but react-router v4 has breaking changes throughout the codebase, including the method for server rendering. In v4, there is a new component specifically for server rendering - StaticRouter.

Take a look at the documentation here for Server rendering: https://reacttraining.com/react-router/web/guides/server-rendering

If you would still like to use the match function as you have it, you could use a version of react-router below version 4. Take a look at my answer on a very similar question from yesterday, you might be using the same boilerplate/example as the other OP.



来源:https://stackoverflow.com/questions/42821551/routing-universal-apps-nodejs-react-error-0-reactrouter-match-is-not-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!