使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
对于这一个,谁不控制服务器端,因此使用哈希路由器v2:
将历史记录放入单独的文件(例如app_history.js ES6):
import { useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });
export default appHistory;
并在任何地方使用它!
react router(app.js ES6)的入口点:
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Redirect } from 'react-router'
import appHistory from './app_history'
...
const render((
<Router history={appHistory}>
...
</Router>
), document.querySelector('[data-role="app"]'));
任何组件(ES6)内的导航:
import appHistory from '../app_history'
...
ajaxLogin('/login', (err, data) => {
if (err) {
console.error(err); // login failed
} else {
// logged in
appHistory.replace('/dashboard'); // or .push() if you don't need .replace()
}
})
其他回答
如果您正在使用哈希或浏览器历史记录,那么您可以
hashHistory.push('/login');
browserHistory.push('/login');
如果您碰巧通过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组件可能会更好。
仅使用浏览器api,独立于任何库
const navigate = (to) => {
window.history.pushState({}, ",", to);
};
这不会导致整页刷新。您仍然可以使用浏览器后退按钮
只需使用this.props.history.push('/where/to/go');
在React Router v4中实现这一点时面临问题的人。
这里有一个从redux操作导航到React应用程序的工作解决方案。
文件history.js
import createHistory from 'history/createBrowserHistory'
export default createHistory()
文件App.js/Route.jsx
import { Router, Route } from 'react-router-dom'
import history from './history'
...
<Router history={history}>
<Route path="/test" component={Test}/>
</Router>
文件*另一个_File.js或redux文件
import history from './history'
history.push('/test') // This should change the URL and rerender Test component
感谢GitHub上的评论:ReactTraining问题评论