【发布时间】:2018-08-16 03:10:43
【问题描述】:
如果您在<Route> 中有一个<Redirect>,您将获得一个location,并且可以这样做:<Redirect search={props.location.search} hash={props.location.hash} ...。
但是,当直接在顶级<Switch> 内时,<Redirect> 没有任何props.location 可以访问search 和hash。
有没有办法直接在顶级<Switch> 之后的<Redirect> 中保留查询字符串和哈希片段(树中没有更高的<Route>)?
示例:(打字稿)
Router({},
Switch({},
Redirect({ path: '/', to: '/latest', exact: true }))))
将to: '/latest' 更改为to: { pathname:... search:.. hash:.. } 不起作用,因为没有props.location 可用于访问原始.search 和.hash on。
在这里(https://github.com/ReactTraining/react-router/issues/5818#issuecomment-384934176),开发人员说保留查询和哈希问题已经解决,但我找不到在上述情况下有效的任何东西:
> 重定向时保存查询字符串的任何选项?
> 它将在 4.3.0 中实现。在此处查看发行说明:https://github.com/ReactTraining/react-router/releases/tag/v4.3.0-rc.1
这些发行说明链接到:https://github.com/ReactTraining/react-router/pull/5209,其中没有提及任何似乎可行的内容。
也许他们已经只在<Route> 中表示<Redirect> 了?然后,可以执行以下操作:
Route({ path: ..., render: (props) => function() {
Redirect({ to: { pathname:... search: props.location.search, ... } ...}));
【问题讨论】:
-
Route版本有问题吗?您可以只编写一次并在任何地方使用它:
let LocationRedirect = p => <Route render={rp => <Redirect to={p.to(rp)} />} />或其他东西 -
@azium 是的,代码更多。读起来更复杂。我认为路由的东西已经有点复杂了,添加额外的
<Route并再传递一个级别的道具,使代码更加复杂。无论如何,这也许是最好的解决方案(以防万一)。我喜欢LocationRedirect这个名字。如果您愿意,请随时将其发布为答案......也许写下您认为没有其他解决方案?如果你这么想。 ...如果没有更简单的答案(没有额外的<Route>层)出现,我可以在一周左右接受它。 -
嗯,其他名称:
PathRedirect(比“LocationRedirect”更准确?)或者RedirectPathPreserveQueryFrag。 @azium -
哈哈也许.. 这并不是您问题的真正答案。不过也没那么复杂。把它想象成一个函数而不是一个组件。通常函数会相互包装以提供额外的功能。这样,您只需编写一次,然后在其他任何地方使用“简单”版本。
-
“RedirectPathPreserveQueryFrag”是个糟糕的名字