无法访问对象的属性

时间:2017-04-16 12:01:00

标签: reactjs

enter image description here我无法访问通过props传递给EditField组件的对象的键。当我记录我传递到控制台的道具时,它正确输出对象,但是当我尝试获取该对象的任何键时,我得到一个“未定义的错误”。那个对象怎么了?在图片上是我在做console.log(部门)时得到的对象。看看我的代码:

class EditForm extends React.Component {
render() {
const departments = this.props.departments
const showcasedDepName = this.props.showcasedDepName
const dep = departments.filter(dep => dep.depName === 
showcasedDepName)[0]
return(
      ...irrelevant stuff
      <EditField department={dep}/>
    </form>
  </div>
)
}
}

EditField组件:

class EditField extends React.Component {
render() {
const department = this.props.department
console.log(department.depName) //"undefined", whereas it shows me the correct object when I do console.log(department)
return(
  <div className="edit-dep">
    <div>Department name: <input type="text" value=
{department.depName}/></div>
  </div>
)
}
}

1 个答案:

答案 0 :(得分:0)

我修好了!问题来自于我没想到它会来的地方。我计算了componentDidMount函数中的worker数量,其中我将'depAmount'键的状态从null更改为worker数组的长度。当我用componentWillMount替换componentDidMount时,问题就消失了。我想我之所以遇到这个错误的原因是最初用null值渲染的状态。