【发布时间】:2019-02-20 16:13:33
【问题描述】:
当组件在componentWillUpdate 或componentDidUpdate 内重复调用setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
由于此错误,我无法路由到 authenticationRoute 目的地。
控制台输出:
index.js:1446 组件出现上述错误:
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 );
【问题讨论】:
-
哥们,你确定
this.props.authRedirectPath不是未定义的吗? -
好吧,有时问题会退回到您在其中呈现 Auth.js 的组件,向我们展示 App.js
-
您的代码似乎没有包含您在 componentDidUpdate 或 componentWillUpdate 中更新状态的位置,但为什么不构建一个包含所有状态更新的对象,然后只调用一次 setState?跨度>
-
class App extends Component { render() { if ( this.state.isAuthenticated ) { routes = ( <Layout> <Switch> <Route path="/home" component={Home} /> <Redirect to="/auth" /> </Switch> </Layout> ); } return ( <div className='App'> {routes} </div> ); } } const mapStateToProps = state => { return { isAuthenticated: state.isAuthenticated }; }; -
@MikeFeltman 是的,我正在使用 redux 商店来管理我的大部分状态。因为在这个组件中使用了 isAuthenticated。我在那里初始化它并使用 MapStatetoProps
标签: javascript reactjs