【发布时间】:2018-08-16 06:24:25
【问题描述】:
这可能是我应该知道的,但是当我传递一个不带括号的函数时,我不太了解我的组件的行为。这是我的组件代码。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import AppBar from 'material-ui/AppBar';
import LoginButton from './LoginButton';
import LogoutButton from './LogoutButton';
class Header extends Component {
renderButton() {
switch (this.props.auth) {
case null:
return
case false:
return <LoginButton />
default:
return <LogoutButton />
}
}
handleTitleClick() {
return(
<Link to={this.props.auth ? '/classes' : '/'}>
QueueMe
</Link>
);
}
render() {
const styles = {
title: {
cursor: 'pointer',
},
};
return(
<AppBar
title={<span style={styles.title}>QueueMe</span>}
onTitleClick={this.handleTitleClick()}
iconElementRight={this.renderButton()}
showMenuIconButton={false}
/>
);
}
}
/*
* @input: redux state
* Allows the component to access certain piece of the state as props
* Reducers determine the key in the state
*/
function mapStateToProps(state) {
return { auth: state.auth };
}
export default connect(mapStateToProps)(Header);
对于<AppBar> 中的onTitleClick 属性,当我传递它handleTitleClick() 时,我得到了预期的行为,但是当我传递它handleTitleClick 并单击它时,我得到一个错误,显示Cannot read property 'auth' of undefined。究竟是什么区别导致handleTitleClick 不知道状态?
【问题讨论】:
-
ReactJS 文档:reactjs.org/docs/…
-
您检查过
this等于handleTitleClick的内部吗? -
@RaphaMex 这正是我的想法,但是当我通过不带括号的函数时出现未定义的错误
-
@DanO 出于某种原因,当我在不带括号的情况下传递函数时,状态不是
this的一部分,但是当我用括号传递函数时,不知道它为什么会这样以及如何去围绕它 -
没有括号,您实际上并没有调用该函数。不带括号的函数名是对该函数的引用。阅读更多teamtreehouse.com/community/…
标签: reactjs redux react-redux material-ui