我收到错误" TypeError:无法读取属性' isFollowing' of null"对于以下代码:
import React from 'react';
import styles from './Cover.css';
import withStyles from '../../../../decorators/withStyles';
import Link from '../../../../utils/Link';
import Avatar from './Avatar';
import classnames from 'classnames';
import { Button } from 'react-bootstrap';
@withStyles(styles)
class Cover extends React.Component {
toggleFollow () {
this.setState({isFollowing: !this.state.isFollowing});
}
render() {
var user = this.props.user;
var followClass = this.state.isFollowing? 'active': '';
return (
<div className="Cover">
<div className="Cover-container">
<div>
<Avatar
username= {user}
profession="Web Developer"
location="New York, New York"
status="I am here to protect my business, a bunch of kids are out to ruin me" />
<div className="Cover-submenu-container">
<div className="Cover-submenu-section">
.
</div>
<div className="Cover-submenu-section links">
<a href="#" className="Cover-submenu-link">
<i className="fa fa-twitter"></i>
</a>
<a href="#" className="Cover-submenu-link">
<i className="fa fa-facebook"></i>
</a>
</div>
<div className="Cover-submenu-section connect-menu">
<Button className={classnames('follow-btn', {followClass})} href="#" onClick={this.toggleFollow.bind(this)}>Follow</Button>
<Button className="connect-btn" href="#" onClick={this.followBtn.bind(this)}>Connect</Button>
<Button className="follow-btn" href="#" onClick={this.followBtn.bind(this)}>Follow</Button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Cover;
我无法弄清楚我在这里做错了什么,我很反应犹新。有什么想法吗?非常感谢。
答案 0 :(得分:1)
您需要做的第一件事是添加isFollowing属性的初始值。因为您使用的是ES6语法,所以可以在构造函数中执行此操作。只需在toggleFollow()函数之前添加此代码:
constructor(props) {
super(props);
this.state = {
isFollowing: false
}
}
第二个错误(基于你问题的评论)来自没有定义函数followBtn()。在render()函数之前添加它:
followBtn() {
alert('followBtn called'); //change it for whatever you want
}
不要忘记点击两个按钮(连接,跟随)现在会产生相同的结果,因为将调用相同的功能。