2017-04-26 170 views
1

我试图从初始状态对象映射对象属性。我可以获得除嵌套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> 
 
    ); 
 
    } 
 
}

和状态:

enter image description here

I am getting Cannot convert undefined or null to object from this row {Object.keys(this.state.dataGoal.milestones).map((milestoneKey) => {...}

但在呈现右上面方法的description行渲染就好了。任何人有一些想法,请?

谢谢 的Jakub

回答

3

使用Object.keys()之前把支票上dataGoal,像这样:

this.state.dataGoal.milestones && Object.keys(this.state.dataGoal.milestones)

原因:您是从服务器需要时间获取数据,直到this.state.dataGoal.milestones将是undefined

或者你可以保持渲染,直到你没有通过在状态变量中使用bool来获取数据。

检查这一点,就会产生同样的错误:

let a = {}; 
 

 
Object.keys(a.a).map(el => console.log(el));

建议:结合lifecycle methods不需要,直接使用它们,所以用lifecycle methods删除arrow function

+0

非常感谢@Mayank的所有建议。我认为它必须做些什么,我不能使它工作。有关上述代码的任何其他建议?我对React很陌生,所以对我的帮助表示赞赏。再次感谢。 –

+1

休息一切都是正确的,还有一件事是我想建议你(我曾经跟随),尽量使渲染方法尽可能小意味着如果你想运行一些循环来创建UI或其他JS条件,把它放在一个函数并调用渲染函数,它将帮助您管理代码和其他人,以了解您在做什么:) –

+0

感谢您的修改和建议。 :) –

相关问题