【发布时间】:2017-07-07 16:43:00
【问题描述】:
我正在为我的 React/Express 应用程序实现服务器端渲染 - 该应用程序实际上可以按预期工作,但我在服务器上收到与 match() 和 RouterContext 相关的警告,我'想了解和解决。
基本上,在match 的回调函数中,参数(err, redirect, props) 的计算结果都是undefined。
index.js(Express 应用根目录):
'use strict'
require('babel-register')({
presets: ['es2015', 'react']
});
const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext, createRoutes } = reactRouter
app.get('*', (req, res) => {
match({ routes: createRoutes(routes), location: req.url }, (err, redirect, props) => {
const appHtml = renderToString(React.createElement(RouterContext, props))
res.send(renderPage(appHtml))
})
})
因此,如果我将console.log() 放入err、redirect 和props,它们都会返回undefined。这会导致我的服务器返回警告
Warning: Failed prop type: The prop `router` is marked as required in `RouterContext`, but its value is `undefined`.
in RouterContext
Warning: Failed prop type: The prop `location` is marked as required in `RouterContext`, but its value is `undefined`.
in RouterContext
Warning: Failed prop type: The prop `routes` is marked as required in `RouterContext`, but its value is `undefined`.
in RouterContext
Warning: Failed prop type: The prop `params` is marked as required in `RouterContext`, but its value is `undefined`.
in RouterContext
Warning: Failed prop type: The prop `components` is marked as required in `RouterContext`, but its value is `undefined`.
in RouterContext
Warning: Failed child context type: The child context `router` is marked as required in `RouterContext`, but its value is `undefined`.
in RouterContext
再次令我惊讶的是,我的应用程序似乎运行良好 - 我可以刷新页面、直接访问 url(即“localhost:3000/person/1234”),但这些警告仍然存在。也许我不明白RouterContext 的需求(可能)。
无论如何,我想解决这个问题,因为我想使用这些参数来设置一些条件......对此的任何指导将不胜感激。
更新
我意识到err 和redirect 应该默认为undefined(除非有错误或重定向),但无论我做什么,props 似乎也卡在未定义上。
来自https://knowbody.github.io/react-router-docs/api/match.html:“如果所有三个参数都是undefined,这意味着没有找到与给定位置匹配的路线。”
但我不明白 - 该应用程序似乎运行良好。什么给了?
【问题讨论】:
-
err应该默认为undefined,除非出现错误。如果props也未定义,是不是有一些错误? -
是的 - 请参阅我在问题底部所做的“更新”。不过,您不使用 createRoutes 是对的——这里不合适。我想通了,看看我的答案。
标签: reactjs express react-router