在一个应用程序上工作,用户可以输入标题,他们的名字和段落来提交一个故事,然后存储在Firestore数据库中。然而,尽管我输入了一些文本,但当我按下submit按钮调用storeData()时,console.log(firebase.firestore.collection('story'))是"object Object“,而console.log(this.state)是"undefined",尽管我已经在构造函数中清楚地定义了它。
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>
);
}
}```发布于 2021-05-17 23:41:06
传递给事件处理程序的函数(如onPress )将丢失其隐式绑定的“this”上下文,当调用该函数时,该上下文将被设置为未定义。
您有两个选项,您可以使用bind方法显式绑定'this‘的上下文,例如
<TouchableOpacity style={styles.button} onPress={this.storeData.bind(this)}>
<Text>Submit</Text>
</TouchableOpacity>或者使用箭头函数,它将“this”的上下文绑定到定义该函数的范围,例如
// 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>https://stackoverflow.com/questions/67572713
复制相似问题