使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
在基于类的组件中编程导航。
import { Redirect } from "react-router-dom";
class MyComponent extends React.Component{
state = {rpath: null}
const goTo = (path) => this.setState({rpath: path});
render(){
if(this.state.rpath){
return <Redirect to={this.state.rpath}/>
}
.....
.....
}
}
其他回答
在React Router v4中,我遵循这两种方式以编程方式进行路由。
this.props.history.push(“/某物/某物”)this.props.history.replace(“/ssomething/something”)
第二个
替换历史堆栈上的当前条目
要获取道具中的历史记录,您可能必须使用
带路由器
InReact路由器v6
import { useNavigate } from "react-router-dom";
function Invoices() {
let navigate = useNavigate();
return (
<div>
<NewInvoiceForm
onSubmit={async event => {
let newInvoice = await createInvoice(event.target);
navigate(`/invoices/${newInvoice.id}`);
}}
/>
</div>
);
}
React Router v6入门
如果您正在使用哈希或浏览器历史记录,那么您可以
hashHistory.push('/login');
browserHistory.push('/login');
对于React路由器v4+
假设在初始渲染过程中不需要导航(可以使用<Redirect>组件),这就是我们在应用程序中所做的。
定义返回null的空路由。这将允许您访问历史对象。您需要在定义路由器的顶层执行此操作。
现在,您可以在历史上做所有可以做的事情,如history.push()、history.replace()、history.go(-1)等。!
import React from 'react';
import { HashRouter, Route } from 'react-router-dom';
let routeHistory = null;
export function navigateTo(path) {
if(routeHistory !== null) {
routeHistory.push(path);
}
}
export default function App(props) {
return (
<HashRouter hashType="noslash">
<Route
render={({ history }) => {
routeHistory = history;
return null;
}}
/>
{/* Rest of the App */}
</HashRouter>
);
}
要将withRouter与基于类的组件一起使用,请尝试以下操作。不要忘记将导出语句更改为与Router一起使用:
从“react router dom”导入{withRouter}
class YourClass extends React.Component {
yourFunction = () => {
doSomeAsyncAction(() =>
this.props.history.push('/other_location')
)
}
render() {
return (
<div>
<Form onSubmit={ this.yourFunction } />
</div>
)
}
}
export default withRouter(YourClass);
对于已经使用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