为什么添加onClick方法会在我的react render方法中导致无限循环

时间:2016-11-30 23:02:20

标签: reactjs

我有一行似乎导致无限循环。如果我将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);

1 个答案:

答案 0 :(得分:1)

您不需要在onClick属性中调用该函数,只需传递该函数,因此它必须是:

  // 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>;
  }