[英]Cannot convert undefined or null to object in react
我正在尝试从初始状态对象映射对象属性。 除了嵌套的milesotnes
我可以获取所有属性。
初始状态在组件类构造函数中定义,如下所示:
class GoalView extends Component { constructor(props) { super(props); this.state = { dataGoal: {}, uid: firebaseAuth().currentUser.uid, currentGoalId: this.props.match.params.goalId, }; } componentDidMount = () => { const dataGoalRef = dbRef.child('goals/'+this.state.uid+'/'+this.state.currentGoalId); dataGoalRef.on('value', snap => { this.setState({ dataGoal: snap.val(), currentGoalId: this.props.match.params.goalId, }); }); } componentWillUnmount = () => { this.state = { currentGoalId: null, }; } ... }
我从React Router V4链接获取currentGoalId
:
<Link title="Open goal" to={"/app/goal/id"+key}>Open goal</Link>
在较高阶的组件中。 当前GoalView组件的render方法如下所示:
render() { return( <div> <main className="content"> <p>{this.state.dataGoal.description}</p><br /><br /> {Object.keys(this.state.dataGoal.milestones).map( (milestoneKey) => { const milestonesData = this.state.dataGoal.milestones[milestoneKey]; return <div className="milestone-wrap" key={milestoneKey}> <label className="milestone-label truncate">{milestonesData.name}</label> </div> })} </main> </div> ); } }
和状态:
我正在
Cannot convert undefined or null to object
从该行{Object.keys(this.state.dataGoal.milestones).map( (milestoneKey) => {...}
但是该行上方的render方法中的description
可以很好地渲染。 有人有什么想法吗?
谢谢雅库布
在使用Object.keys()
之前,将检查放在dataGoal
,如下所示:
this.state.dataGoal.milestones && Object.keys(this.state.dataGoal.milestones)
原因:从服务器获取数据需要时间,直到this.state.dataGoal.milestones
被取消undefined
。
或者,您可以保留渲染,直到通过使用bool
in state变量获取数据为止。
对此进行检查,将产生相同的错误:
let a = {}; Object.keys(aa).map(el => console.log(el));
建议:不需要绑定lifecycle methods
,请直接使用它们,因此请删除带有lifecycle methods
的arrow function
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.