构造函数元素未定义并返回错误

时间:2017-07-17 01:23:19

标签: reactjs

简单的问题,但我无法弄清楚解决方案。我在文本框上有一个简单的字符计数器,它按预期工作,但是,我在constructorcomponentWillReceiveProps时遇到问题。我收到错误.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,
  });
}

1 个答案:

答案 0 :(得分:0)

似乎正在运行的解决方案是使用if语句并放弃const以支持var。我不确定为什么会有效。

if(summary == null) {
    var count = 0;
  } else {
    var count = 3000 - (profileCandidateCollection && profileCandidateCollection.summary.length);
  }

  this.setState({
    count: count
  });
  }