使用Reaction-路由器以编程方式导航我正在开发一个应用程序,在这个应用程序中,我检查用户是否不是。loggedIn我必须显示登录表单,否则dispatch阿action这将改变路由并加载其他组件。这是我的代码: render() {
if (isLoggedIn) {
// dispatch an action to change the route
}
// return login component
<Login />
}如何实现这一点,因为我不能在呈现函数中更改状态。
3 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
react-router v4
withRouterhistory.pushwithRouterRouter
import {withRouter} from 'react-router';class App extends React.Component {
...
componenDidMount() {
// get isLoggedIn from localStorage or API call
if (isLoggedIn) {
// dispatch an action to change the route
this.props.history.push('/home');
}
}
render() {
// return login component
return <Login />
}}export default withRouter(App);重要注记
如果你用 withRouter若要防止更新被 shouldComponentUpdate,重要的是 withRouter包装实现 shouldComponentUpdate..例如,在使用Redux时:
/这到处都是 shouldComponentUpdatewithRouter(connect(...)(MyComponent))
/这不是 connect(...)(withRouter(MyComponent))
import {withRouter} from 'react-router';class App extends React.Component {
...
render() {
if(isLoggedIn) {
return <Redirect to="/home"/>
}
// return login component
return <Login />
}}react-router v2 or react-router v3context
class App extends React.Component {
...
render() {
if (isLoggedIn) {
// dispatch an action to change the route
this.context.router.push('/home');
}
// return login component
return <Login />
}}App.contextTypes = {
router: React.PropTypes.object.isRequired}export default App;import { browserHistory } from 'react-router';browserHistory.push('/some/path');添加回答
举报
0/150
提交
取消
