使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
在我的回答中,有三种不同的方法可以通过编程重定向到路由。已经介绍了一些解决方案,但下面的解决方案仅针对具有附加演示应用程序的功能组件。
使用以下版本:
反应:16.13.1反应时间:16.13.1反应路由器:5.2.0反应路由器dom:5.2.0字体:3.7.2
配置:
因此,首先解决方案是使用HashRouter,配置如下:
<HashRouter>
// ... buttons for redirect
<Switch>
<Route exact path="/(|home)" children={Home} />
<Route exact path="/usehistory" children={UseHistoryResult} />
<Route exact path="/withrouter" children={WithRouterResult} />
<Route exact path="/redirectpush" children={RedirectPushResult} />
<Route children={Home} />
</Switch>
</HashRouter>
从有关<HashRouter>的文档中:
一个<Router>,它使用URL的哈希部分(即window.location.hash)来保持UI与URL同步。
解决:
使用<Redirect>使用useState推送:
在功能组件(我的存储库中的RedirectPushAction组件)中使用,我们可以使用useState来处理重定向。棘手的是,一旦发生重定向,我们需要将重定向状态设置回false。通过使用带有0延迟的setTimeOut,我们等待React提交重定向到DOM,然后返回按钮,以便下次使用。
请在下面找到我的示例:
const [redirect, setRedirect] = useState(false);
const handleRedirect = useCallback(() => {
let render = null;
if (redirect) {
render = <Redirect to="/redirectpush" push={true} />
// In order wait until committing to the DOM
// and get back the button for clicking next time
setTimeout(() => setRedirect(false), 0);
}
return render;
}, [redirect]);
return <>
{handleRedirect()}
<button onClick={() => setRedirect(true)}>
Redirect push
</button>
</>
从<Redirect>文档:
渲染<重定向>将导航到新位置。新位置将覆盖历史堆栈中的当前位置,就像服务器端重定向(HTTP 3xx)那样。
使用useHistory钩子:
在我的解决方案中,有一个名为UseHistoryAction的组件,它表示以下内容:
let history = useHistory();
return <button onClick={() => { history.push('/usehistory') }}>
useHistory redirect
</button>
useHistory钩子允许我们访问历史对象,它帮助我们以编程方式导航或更改路线。
使用withRouter,从道具获取历史记录:
创建了一个名为WithRouterAction的组件,显示如下:
const WithRouterAction = (props:any) => {
const { history } = props;
return <button onClick={() => { history.push('/withrouter') }}>
withRouter redirect
</button>
}
export default withRouter(WithRouterAction);
阅读路由器文档:
您可以通过withRouter高阶组件访问历史对象的财产和最接近的<Route>匹配项。无论何时渲染,withRouter都会将更新的匹配、位置和历史属性传递给包装组件。
演示:
为了更好地表示,我用这些示例构建了一个GitHub存储库,请在下面找到它:
React Router程序化重定向示例
其他回答
也许不是最好的解决方案,但它可以完成任务:
import { Link } from 'react-router-dom';
// Create functional component Post
export default Post = () => (
<div className="component post">
<button className="button delete-post" onClick={() => {
// ... delete post
// then redirect, without page reload, by triggering a hidden Link
document.querySelector('.trigger.go-home').click();
}}>Delete Post</button>
<Link to="/" className="trigger go-home hidden"></Link>
</div>
);
基本上,与一个操作相关的逻辑(在本例中为删除后操作)最终将调用重定向触发器。这并不理想,因为您将在标记中添加DOM节点“触发器”,以便在需要时方便地调用它。此外,您将直接与DOM交互,这在React组件中可能是不需要的。
不过,这种类型的重定向并不经常需要。因此,在组件标记中添加一两个额外的隐藏链接并不会造成太大的伤害,特别是如果您为它们提供了有意义的名称。
对于已经使用React Router v6的用户,可以使用React Router提供的useNavigate钩子来完成。
使用此钩子进行导航非常简单:
import { generatePath, useNavigate } from 'react-router';
navigate(-1); // navigates back
navigate('/my/path'); // navigates to a specific path
navigate(generatePath('my/path/:id', { id: 1 })); // navigates to a dynamic path, generatePath is very useful for url replacements
React路由器v6
我已经有一段时间没有接触过React了,但我想感谢并强调Shimrit Snapir的以下评论:
在React Router 6.0上,<Redirect/>更改为<Navigator/>
React路由器V4
tl:dr;
if (navigate) {
return <Redirect to="/" push={true} />
}
简单而声明性的答案是,需要将<Redirectto={URL}push={boolean}/>与setState()结合使用
push:boolean-如果为true,重定向将向历史中推送一个新条目,而不是替换当前条目。
import { Redirect } from 'react-router'
class FooBar extends React.Component {
state = {
navigate: false
}
render() {
const { navigate } = this.state
// Here is the important part
if (navigate) {
return <Redirect to="/" push={true} />
}
// ^^^^^^^^^^^^^^^^^^^^^^^
return (
<div>
<button onClick={() => this.setState({ navigate: true })}>
Home
</button>
</div>
)
}
}
这里有一个完整的例子。在这里阅读更多信息。
PS.该示例使用ES7+属性初始化器初始化状态。如果你感兴趣的话,也可以看看这里。
如果您碰巧通过react router redux将RR4与redux配对,那么也可以使用react router-redux中的路由操作创建器。
import { push, replace, ... } from 'react-router-redux'
class WrappedComponent extends React.Component {
handleRedirect(url, replaceState = true) {
replaceState
? this.props.dispatch(replace(url))
: this.props.dispatch(push(url))
}
render() { ... }
}
export default connect(null)(WrappedComponent)
如果您使用redux thunk/saga来管理异步流,请在redux操作中导入上述操作创建者,并使用mapDispatchToProps连接到React组件可能会更好。
只需使用this.props.history.push('/where/to/go');