问题描述
我正在开发一个应用程序,我在其中检查用户是否 loggedIn
我必须显示登录表单,否则 dispatch
一个动作
,它会改变路线并加载其他组件。这是我的代码:
I am developing an application in which i check if the user is not loggedIn
I have to display the login form, else dispatch
an action
that would change the route and load other component. Here is my code:
render() {
if (isLoggedIn) {
// dispatch an action to change the route
}
// return login component
<Login />
}
我如何实现这一点,因为我无法改变渲染功能中的状态。
How can i achieve this as i cannot change states inside render function.
推荐答案
考虑到您使用 react-router v4
将您的组件与 withRouter
一起使用,并使用道具中的 history.push
来更改路线。只有当你的组件没有收到路由器
道具时,你才需要使用 withRouter
,这可能发生在您的组件是由路由器呈现的组件的嵌套子组件,并且您没有将Router支持传递给它,或者当组件根本没有链接到路由器并且从路由呈现为单独的组件时。
Use your component with withRouter
and use history.push
from props to change the route. You need to make use of withRouter
only when your component is not receiving the Router
props, this may happen in cases when your component is a nested child of a component rendered by the Router and you haven't passed the Router props to it or when the component is not linked to the Router at all and is rendered as a separate component from the Routes.
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时:
If you are using withRouter
to prevent updates from being blocked by shouldComponentUpdate
, it is important that withRouter
wraps the component that implements shouldComponentUpdate
. For example, when using Redux:
//这大概是 shouldComponentUpdate
withRouter(connect(...)(MyComponent))
//这不是
connect(...)(withRouter(MyComponent))
或者你可以使用Redirect
or you could use Redirect
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或者react-router v3
,你可以利用 context
动态改变路线,如
With react-router v2 or react-router v3
, you can make use of context
to dynamically change the route like
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');
这篇关于以编程方式使用react-router进行导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!