我正在使用 react-router-dom
我猜这是导致问题的原因,但我不知道从哪里开始寻找或如何解决它。我也收到类似 Warning: Did not expect server HTML to contain a <nav> in <div>
的错误.
正如我所说,我不太确定去哪里找,所以如果您认为有某些代码会有所帮助,请告诉我,我会发布它。否则,我可以发布我用来执行 SSR 的代码。
编辑:确切错误:Warning: Prop
引用资料 did not match. Server: "/profile/5a073dc44cb45b00125e5c82" Client: "profile/5a073dc44cb45b00125e5c82"
我检查了客户端,它有 /profile/:id
所以不确定它在哪里说没有 /
,至于 <nav>
的另一个错误在<div>
, 我有一个 nav
在我的标题中,但我真的不确定如何去“修复”它。
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { renderRoutes } from 'react-router-config';
import serialize from 'serialize-javascript';
import { Helmet } from 'react-helmet';
import { matchRoutes } from 'react-router-config';
import routes from './src/routes';
import createStore from './src/stores';
function handleRender(req, res) {
let initial = {};
if (req.vertexSession != null && req.vertexSession.user != null) {
initial.user = { currentUser: req.vertexSession.user };
}
const store = createStore.configure(initial); // create Store in order to get data from redux
const promises = matchRoutes(routes, req.path)
.map(({ route, match }) => {
// Matches the route and loads data if loadData function is there
return route.loadData
? route.loadData(store)
: route.loadDataWithMatch ? route.loadDataWithMatch(store, match) : null;
})
.map(promise => {
if (promise) {
return new Promise((resolve, reject) => {
promise.then(resolve).catch(resolve); // lets all data load even if route fails
});
}
});
Promise.all(promises).then(() => {
const context = {};
if (context.url) {
return res.redirect(301, context.url); // redirect for non auth users
}
if (context.notFound) {
res.status(404); // set status to 404 for unknown route
}
const content = renderToString(
<Provider store={store}>
<StaticRouter location={req.path} context={context}>
<div>{renderRoutes(routes)}</div>
</StaticRouter>
</Provider>
);
// console.log(store.getState());
const initialState = serialize(store.getState());
const helmet = Helmet.renderStatic();
res.render('index', { content, initialState, helmet });
});
}
module.exports = handleRender;
最佳答案
你已经解决了吗?我的 react 应用程序遇到了类似的问题并修复了它。这是我的问题:
<Link to="./shop">Shop</Link>
我的修复:
<Link to="/shop">Shop</Link>
无论您使用服务器渲染什么,都是问题所在。我建议梳理一下你的路线模块,看看你是否忘记了某处的正斜杠。如果这不起作用,请查看您在路由文件中导入的组件。
关于javascript - 警告 Prop `href` 不匹配。使用 React 服务器端渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47336589/