我正在开发一个应用程序,我在其中检查用户是否未loggedIn
。我必须显示登录表单,否则 dispatch
将更改路由并加载其他组件的 action
。这是我的代码:
render() {
if (isLoggedIn) {
// dispatch an action to change the route
}
// return login component
<Login />
}
我如何实现这一点,因为我无法在 render
函数中更改状态。
最佳答案
考虑到您正在使用 react-router v4
将您的组件与 withRouter
一起使用,并使用 props 中的 history.push
来更改路由。只有当您的组件没有接收到 Router
属性时,您才需要使用 withRouter
,这可能发生在您的组件是由Router 并且您还没有将 Router props 传递给它,或者当组件根本没有链接到 Router 并且呈现为独立于 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);
Important Note
If you are using
withRouter
to prevent updates from being blocked byshouldComponentUpdate
, it is important thatwithRouter
wraps the component that implementsshouldComponentUpdate
. For example, when using Redux:// This gets around
shouldComponentUpdate
withRouter(connect(...)(MyComponent))
// This does not
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 或 react-router v3
,您可以使用 context
动态更改路由,例如
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');
关于javascript - 使用 react-router 以编程方式导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127739/