我在Next JS中有一个带redux的简单登录表单。
我的初始user
状态为:
{
user: {}
}
,在表单提交后,将出现login dispatch
。状态为:
{
user: {
authenticated: true",
....
}
}
因此,无论何时提交表单,我都希望可以通过mapStateToProps轻松获得authenticated
。因此,我有一个条件要检查authenticated
是否正确,以便现在可以redirect
从登录表单到仪表板。
代码是:
static getDerivedStateFromProps(props, state) {
const user = props.user.user
if (user && user.authenticated) {
Router.push('/dashboard') =====> culprit?
}
return null
}
但是,我收到Cannot update during an existing state transition
控制台警告。
我最初使用componentWillReceiveProps
,但令我惊讶的是,文档说应该避免使用它,因为它变成了遗留代码。
为什么会这样?是因为错误的生命周期吗?我还尝试了shouldComponentUpdate
等,但是它也无法正常工作。
我应该如何正确实施?
下面的完整代码:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faLock } from '@fortawesome/free-solid-svg-icons'
import Router from 'next/router'
import { login } from '../actions'
class Login extends Component {
state = {
username: 'admin',
password: 'Password',
}
static getDerivedStateFromProps(props, state) {
const user = props.user.user
if (user && user.authenticated) {
Router.push('/dashboard') =======> culprit?
}
return null
}
handleChange = e => {
const { name, value } = e.target
this.setState({ [name] : value })
}
handleSubmit = e => {
e.preventDefault()
this.props.login(this.state)
}
render() {
const { username, password } = this.state
return (
<div id="content">
<div className="logo">
<div className="">
<div><img src="/static/images/login1.png" alt="Login1" align="left" /></div>
</div>
<div className="">
<div><img src="/static/images/login2.png" alt="Login2" align="left" width="350" /></div>
<div><p><span className="system_name">Information System v1.0</span></p></div>
</div>
</div>
<div className="login">
<div className="header">
<div className="text">
<div className="lock">
<center>
<FontAwesomeIcon icon={faLock} />
</center>
</div>
</div>
<p>LOGIN</p>
</div>
<div className="content">
<form onSubmit={e => this.handleSubmit(e)}>
<p>Please login to access all our features</p>
<input
type="text"
placeholder="Username"
name="username"
value={username}
autoComplete="off"
onChange={this.handleChange}
/>
<input
type="password"
placeholder="Password"
name="password"
value={password}
autoComplete="off"
onChange={this.handleChange}
/>
<button
type="submit"
>
<span>{this.props.user.isLoading ? 'Logging In....' : 'Login'}</span>
</button>
</form>
<a href="#">Forgot Password?</a>
</div>
</div>
</div>
)
}
}
const mapStateToProps = ({user}) => ({
user,
})
export default connect(mapStateToProps, { login })(Login)