我正在从render函数调用displayElements并得到以下错误:TypeError: Cannot read property 'loading' of undefined
。为什么会显示此错误?我认为出现此错误的原因是,在初始渲染时将没有任何结果。但是,当单击提交按钮时,将执行对数据库的查询,我想使用displayElements显示结果。
displayElements(){
var data = this.props.getObjectsQuery;
console.log(this.props);
if(data.loading){
return <option disabled>Loading...</option>;
}else{
return data.action.map(action => {
return(<option key={action.action} value={action.timestamp}>{action.filename}</option>);
})
}
}
提交按钮
handleSubmit = event => {
event.preventDefault();
console.log(this.state);
this.setState({
startTime: new Date(document.getElementById("startTime").value).valueOf(),//getElementById is a jQuery method
endTime: new Date(document.getElementById("endTime").value).valueOf()
}, () => {
this.props.data.refetch({//Assign the inputvalues, which is the current state, to the variables after pressing the submit button
startTime: this.state.startTime,
endTime:this.state.endTime
});
console.log(this.state.startTime);
console.log(this.state.endTime);
});
};
答案 0 :(得分:1)
将条件写为if(data)
,然后编写代码。
displayElements(){
var data = this.props.getObjectsQuery;
console.log(this.props);
if(data) {
if(data.loading){
return <option disabled>Loading...</option>;
}else{
return data.action.map(action => {
return(<option key={action.action} value={action.timestamp}>{action.filename}</option>);
})
}
}
}