未定义不是对象 ->反应本机 JS



my Code是:

import Note from './Note';
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
noteArray: [],
noteText: '',
}
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}></Note>
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Yapılacaklar Listesi</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
placeholder='Notunuz...'
placeholderTextColor='white'
underlineColorAndroid='transparent'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote.bind(this) } style={styles.addButton} >
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</View>
);

}
addNote()
{
if (this.state.noteText){
var d=new Date;
this.state.noteArray.push({
'date':d.getFullYear()
+'/'+(d.getMonth()+1)
+'/'+d.getDate()
});
this.setState({ noteArray: this.state.NoteArray })
this.setState({ noteText: '' })
}
}
}

我的错误是:未定义不是一个对象(评估"this.state.noteArray.map"(

我该如何解决这个问题?

我开始学习反应。错误的屏幕是 错误屏幕 这是我的第一个例子。:)

你必须确保你的数组存在:

let notes = !!this.state.noteArray && this.state.noteArray.map((val, key)=>{

应该做这项工作。 这!!是双重否定,以避免另一个典型错误。

这样,如果 noteArray 不存在,则 && 之后的第二部分不会被执行。您可以更进一步并添加安全检查,例如检查它是否确实是一个数组等,但使用上面的行,只要您实际上有一个数组,它就应该可以工作。

最新更新