[英]React Native - this.state coming as undefined despite being defined?
開發一個應用程序,用戶可以輸入標題、姓名和段落來提交故事,然后將其存儲在 Firestore 數據庫中。 然而,盡管我輸入了一些文本,但當我按下提交按鈕調用 storeData() 時,console.log(firebase.firestore.collection('story')) 會顯示為“[object Object]”和 console.log(this. state) 作為“未定義”出現,即使我已經在構造函數中明確定義了它。
import {
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableOpacity,
} from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import firebase from 'firebase';
export default class write extends React.Component {
constructor() {
super();
this.state = {
title: '',
author: '',
story: '',
};
}
storeData() {
console.log(firebase.firestore.collection('story'));
console.log(this.state);
firebase.firestore.collection('story').add({
Title: this.state.title,
Author: this.state.author,
Story: this.state.story,
});
}
render() {
return (
<View style={styles.background}>
<Text style={styles.text}>Write your own story here!</Text>
<TextInput
style={styles.text1}
placeholder="Enter your name"
onChangeText={(text) => {this.setState({ title: text })}}></TextInput>
<TextInput
style={styles.text1}
placeholder="Give a title to your story"
onChangeText={(text) => {this.setState({ author: text })}}></TextInput>
<TextInput
multiline={true}
style={styles.text2}
placeholder="Enter your story here"
onChangeText={(storytext) => {
this.setState({ story: storytext });
}}></TextInput>
<TouchableOpacity style={styles.button} onPress={this.storeData}>
<Text>Submit</Text>
</TouchableOpacity>
</View>
);
}
}```
當調用 function 時,傳遞給事件處理程序的函數(例如 onPress)會丟失其隱式綁定的“this”上下文,這將設置為未定義。
您有兩個選擇,您可以使用 bind 方法顯式綁定“this”的上下文,例如
<TouchableOpacity style={styles.button} onPress={this.storeData.bind(this)}>
<Text>Submit</Text>
</TouchableOpacity>
或者使用箭頭 function,它將“this”的上下文綁定到 scope function 定義在,例如
// Now an arrow function
storeData = () => {
console.log(firebase.firestore.collection('story'));
console.log(this.state);
firebase.firestore.collection('story').add({
Title: this.state.title,
Author: this.state.author,
Story: this.state.story,
});
}
<TouchableOpacity style={styles.button} onPress={this.storeData}>
<Text>Submit</Text>
</TouchableOpacity>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.