在我的ReactJS应用程序中,我使用了react路由器,在这里我使用下面的命令重定向页面。
this.context.router.replace(generateProductURL(oProduct));
这将正确地重定向页面,但需要使用200 OK
代码。我想要301以防重定向。有什么帮助吗?
以下是我的服务器代码:
match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500);
hydrateOnClient();
} else if (renderProps) {
loadOnServer({...renderProps, store, helpers: {client}}).then(() => {
const component = (
<Provider store={store} key="provider">
<ReduxAsyncConnect {...renderProps} />
</Provider>
);
const is404 = renderProps.routes.find(r => r.status === 404) !== undefined;
if (is404) {
res.status(404);
} else {
res.status(200);
}
global.navigator = {userAgent: req.headers['user-agent']};
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
});
} else {
res.status(404).send('Not found');
}
发布于 2016-12-22 09:58:56
tl;dr您需要使用replace
函数重定向onEnter
钩子(传递给钩子的第二个参数)。
要理解为什么调用this.context.router.replace
不触发重定向,您需要了解为什么<Redirect>
组件会触发重定向。
什么是<Redirect>
?
与<Route>
组件一样,<Redirect>
不是“真实的”组件,因为它不呈现任何东西。相反,它只是返回一个路由对象。<Redirect>
的路由对象包括一个onEnter
钩子,它调用钩子的replace
方法,提供要重定向到的位置。
replace({
pathname,
query: route.query || location.query,
state: route.state || location.state
})
检测重定向
match
检测重定向的方法是通过onEnter
挂钩。onEnter
钩子的第二个参数是replace
函数。当调用该replace
函数时,它将位置参数存储为redirectInfo
。
let redirectInfo
function replace(location) {
redirectInfo = location
}
现在,当您调用match
时,它会遍历您的所有路由,并确定哪些路由与当前位置(req.url
)匹配。然后它运行任何onLeave
、onChange
和onEnter
钩子(但是只有onEnter
钩子可以用于服务器呈现,因此我们可以忽略这里的其他钩子)。
在运行来自匹配路由的onEnter
钩子时,如果在任何时候它检测到redirectInfo
变量已被设置(由replace
函数设置),则它将调用回调函数传递给match
,为其提供redirectLocation
。
if (error || redirectInfo) {
done(error, redirectInfo) // No need to continue.
}
然后,在match
函数中,使用redirectLocation
触发重定向。
res.redirect(redirectLocation.pathname + redirectLocation.search);
以编程方式重定向
因此,如果您想要重定向自己,则需要在<Route>
的onEnter
钩子中使用replace
函数进行重定向。nextState
将包含匹配的路由以及任何解析的params。
<Route path='product/:productId' onEnter={(nextState, replace) => {
replace(generateProductURL(nextState.params.productId));
}} />
https://stackoverflow.com/questions/41283286
复制相似问题