我试图从初始状态对象映射对象属性。我可以获得除嵌套milesotnes
以外的所有属性。无法将undefined或null转换为对象中的反应
初始状态中的部件类的构造函数定义如下所示:
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,
};
}
...
}
我从一个阵营路由器V4链路获取currentGoalId
:
<Link title="Open goal" to={"/app/goal/id"+key}>Open goal</Link>
这是在更高阶的组件中。当前GoalView分量的渲染方法看起来像这样:
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>
);
}
}
和状态:
I am getting
Cannot convert undefined or null to object
from this row{Object.keys(this.state.dataGoal.milestones).map((milestoneKey) => {...}
但在呈现右上面方法的description
行渲染就好了。任何人有一些想法,请?
谢谢 的Jakub
非常感谢@Mayank的所有建议。我认为它必须做些什么,我不能使它工作。有关上述代码的任何其他建议?我对React很陌生,所以对我的帮助表示赞赏。再次感谢。 –
休息一切都是正确的,还有一件事是我想建议你(我曾经跟随),尽量使渲染方法尽可能小意味着如果你想运行一些循环来创建UI或其他JS条件,把它放在一个函数并调用渲染函数,它将帮助您管理代码和其他人,以了解您在做什么:) –
感谢您的修改和建议。 :) –