Kev*_*ell 9 javascript reactjs
当组件重复调用setState内部componentWillUpdate或时,可能会发生这种情况componentDidUpdate.React限制嵌套更新的数量以防止无限循环.
authenticationRoute由于此错误,我无法路由到目的地.
控制台输出:
index.js:1446组件中出现上述错误:
Run Code Online (Sandbox Code Playgroud)in Redirect (at Auth.jsx:101) in div (at Auth.jsx:116) in Auth (created by Context.Consumer) in Connect(Auth) (created by Route) in Route (at App.js:27) in Switch (at App.js:26) in div (at App.js:46) in App (created by Context.Consumer) in Connect(App) (created by Route) in Route (created by withRouter(Connect(App))) in withRouter(Connect(App)) (at src/index.js:28) in Router (created by BrowserRouter) in BrowserRouter (at src/index.js:27) in Provider (at src/index.js:26)
import React, { Component } from 'react';
import Input from '../../components/Input/input';
import Button from '../../components/Button/button';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import * as service from '../../services/AuthService';
class Auth extends Component {
state = {
controls: {
username: {
//..
},
password: {
//..
},
valid: false,
touched: false
}
}
}
componentDidMount () {
if ( this.props.isAuthenticated && this.props.authRedirectPath !== '/' ) {
this.props.onSetAuthRedirectPath('/home');
}
}
handleSubmit=(event)=> {
event.preventDefault();
this.props.auth(this.state.controls.username.value,this.state.controls.password.value)
}
render() {
let errorMessage = null;
let button= button=<Button btnType="Success">Login</Button>
let authRedirect = null;
if (this.props.isAuthenticated) {
**authRedirect = <Redirect to={this.props.authRedirectPath}/>** //line 101
}
return (
<div>
{authRedirect}
<form onSubmit={this.handleSubmit}>
{form}
{button}
</form>
</div>
)
}
}
export default connect( mapStateToProps, mapDispatchToProps )( Auth );Run Code Online (Sandbox Code Playgroud)
你如何检查身份验证?
最好在 redux-store 中初始化 isAuthenticated 以便您可以在渲染之前在组件中全局使用它
所以,而不是
if (this.state.isAuthenticated) {routes=<div>..</div>}
尝试
if (this.props.isAuthenticated{routes=<div>..</div>}
实例属性
道具
this.props 包含由该组件的调用者定义的道具。有关 props 的介绍,请参阅组件和道具。
状态
this.state 包含特定于此组件的数据,这些数据可能会随着时间而改变。状态是用户定义的,它应该是一个普通的 JavaScript 对象。
有关状态的更多信息,请参阅状态和生命周期。 React.Component 生命周期
永远不要直接改变 this.state,因为之后调用 setState() 可能会替换你所做的改变。将 this.state 视为不可变的。
此外,确保 mapStateToProps 指向您的减速器
return {isAuthenticated : state.{减速器}.isAuthenticated}