使用ReactRouter V4,我可以使用<Switch>
来获取运行<NotFound>
组件的最后一条路径,但我真正想要的是重定向到服务器,然后生成真正的404所以搜索引擎知道不要将404页面本身索引为有效。我的代码如下。我在使用服务器端渲染时找到了如何执行此操作的示例,但在使用仅基于纯客户端的应用程序时却找不到。
export default () => {
return (
<div>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/speakers" component={Speakers}/>
<Route exact path="/login" component={Login}/>
<Route component={NotFound} />
</Switch>
</div>
)
};
const NotFound = () => (
<Status code={404}>
<div>
<h1>Sorry, can’t find that.</h1>
</div>
</Status>
);
const Status = ({ code, children }) => (
<Route render={({ staticContext }) => {
console.log('staticContextx');
if (staticContext) {
console.log('staticContext');
staticContext.status = code;
}
return children
}}/>
);
编辑:添加尝试,但它感觉很糟糕。
我在节点服务器中添加了对重定向到/ NotFound的检查,然后在location.href
组件中添加了<NotFound>
。这感觉不对,给了一些额外的页面闪烁,我不确定搜索引擎将如何处理。愿意接受更好的想法。
Routes.js
const Status = ({code, children}) => (
<Route render={({staticContext}) => {
if (staticContext) {
staticContext.status = code;
} else {
window.location.href="/NotFound";
}
return children
}}/>
);
节点服务器:
import express from 'express';
import React from "react";
import renderer from './renderer';
const path = require('path');
const app = express();
app.use(express.static('public', {
}));
console.log(path.resolve('public','index.html'));
app.get('*', (req, res) => {
if (req.url === '/speakers') {
console.log('URL...:' + req.url);
console.log('speakers URL (no renderer):' + req.url);
res.sendFile(path.resolve('public','index.html'));
}
else if (req.url === '/login'){
//res.redirect('/index.html');
console.log('login URL (renderer)');
res.send(renderer(req));
}
else if (req.url === '/NotFound') {
res.set("Content-Type", "text/plain");
res.status(404).end("Not found, 404 status returned");
}
else {
console.log('other URL (no renderer)');
res.sendFile(path.resolve('public','index.html'));
}
});
app.listen(3010, () => {
console.log('Listening on port 3010 svcc');
});