简单的问题,但我无法弄清楚解决方案。我在文本框上有一个简单的字符计数器,它按预期工作,但是,我在constructor
和componentWillReceiveProps
时遇到问题。我收到错误.length undefined.
。当长度未定义时,如何使其工作?
constructor(props) {
super(props);
const profileCandidateCollection = props.profileCandidate;
const summary = profileCandidateCollection && profileCandidateCollection.summary;
const count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length);
this.state = {
count: count,
};
}
componentWillReceiveProps(nextProps) {
const profileCandidateCollection = nextProps.profileCandidate;
const summary = profileCandidateCollection && profileCandidateCollection.summary;
const count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length);
this.setState({
count: count,
});
}
答案 0 :(得分:0)
似乎正在运行的解决方案是使用if语句并放弃const
以支持var
。我不确定为什么会有效。
if(summary == null) {
var count = 0;
} else {
var count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length);
}
this.setState({
count: count
});
}