使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
只需使用useNavigate,即可使用最新版本的react
新文件.js
import { useNavigate } from "react-router-dom";
const Newfile = () => {
const navigate = useNavigate();
....
navigate("yourdesiredlocation");
....
}
export default Newfile;
在代码中使用上述的useNavigate功能。
其他回答
React路由器v4和ES6
您可以使用Router和this.props.history.push。
import {withRouter} from 'react-router-dom';
class Home extends Component {
componentDidMount() {
this.props.history.push('/redirect-to');
}
}
export default withRouter(Home);
只需使用this.props.history.push('/where/to/go');
React路由器v2
对于最新版本(v2.0.0-rc5),推荐的导航方法是直接推到历史单例。您可以在组件外部导航文档中看到这一点。
相关摘录:
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
如果使用更新的react router API,则需要在组件内部使用this.props中的历史记录,以便:
this.props.history.push('/some/path');
它还提供pushState,但对于每个记录的警告,它都是不推荐的。
如果使用react router redux,它提供了一个推送功能,您可以这样调度:
import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));
然而,这可能仅用于更改URL,而不是实际导航到页面。
试试React Hook Router,“反应路由器的现代替代品”:
import { useRoutes, usePath, A} from "hookrouter";
要回答OP关于通过选择框链接的问题,您可以这样做:
navigate('/about');
更新的答案
我认为React Hook Router是一个很好的入门套件,帮助我学习了路由,但我后来更新了React Router,了解了它的历史和查询参数处理。
import { useLocation, useHistory } from 'react-router-dom';
const Component = (props) => {
const history = useHistory();
// Programmatically navigate
history.push(newUrlString);
}
您可以将要导航到的位置推到历史位置。
随着React Router v4即将推出,现在有了一种新的实现方式。
import { MemoryRouter, BrowserRouter } from 'react-router';
const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;
<Router location="/page-to-go-to"/>
react lego是一个示例应用程序,展示了如何使用/更新react router,它包括导航应用程序的示例功能测试。