我正在使用react-router-dom
并且我猜这是导致问题的原因,但我不知道哪里开始寻找或如何解决它。我也遇到了Warning: Did not expect server HTML to contain a <nav> in <div>
等错误。
正如我所说,我不确定在哪里看,如果您认为某些代码有用,请告诉我,我会发布。否则,我可以发布我用来做SSR的代码。
编辑:确切错误:Warning: Prop
href 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;
答案 0 :(得分:3)
你有没有解决这个问题?我的反应应用程序遇到了类似的问题并修复了它。这是我的问题:
<Link to="./shop">Shop</Link>
我的修复:
<Link to="/shop">Shop</Link>
无论您使用服务器呈现什么都是问题。我建议梳理你的路线模块,看看你是否忘记了某个地方的正斜线。如果这不起作用,请查看路径文件中导入的组件。
答案 1 :(得分:2)
要添加到 Kevorkian 答案:
确保在所有路由前加上 /
注意 /update
<Link href={{ pathname: '/update', query: { id: product.id } }}>