0
我有一條線,這似乎是導致無限循環。如果我將OnClick處理程序分配給我的元素,則會發生該問題。爲什麼添加一個onClick方法導致無限循環在我的反應渲染方法
所以,在渲染功能,由以下原因引起的無限循環
button = <button onClick={ props.onLogin() }>Login</button>;
相比之下,以下不會引起環
button = <button>Login</button>;
的完整代碼
import React, { Component, PropTypes } from 'react';
import { login, logout } from '../actions/user';
import { connect } from 'react-redux';
class Navbar extends Component {
render() {
const props = this.props;
const { user } = props;
const { isAuthenticated, errorMessage } = user;
let button;
// the onClick assignment below causes the infinite loop
if (isAuthenticated) {
button = <button onClick={ props.onLogout() }>Logout</button>;
} else {
button = <button onClick={ props.onLogin() }>Login</button>;
}
return (
<div>
<a href="/">Hello</a>
<div>
<div>{errorMessage}</div>
{ button }
</div>
</div>
);
}
}
Navbar.propTypes = {
user: PropTypes.object,
errorMessage: PropTypes.string,
};
const mapStateToProps = (state) => {
return {
user: state.user,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onLogin:() => {
dispatch(login());
},
onLogout:() => {
dispatch(logout());
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
啊是的,這就是它! – MonkeyBonkey