React Native - 尽管已定义,但 this.state 仍然未定义?

时间:2021-05-17 15:30:36

标签: javascript firebase react-native google-cloud-firestore

正在开发一款应用,用户可以在其中输入标题、姓名和段落以提交故事,然后将故事存储在 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>
    );
  }
}```

1 个答案:

答案 0 :(得分:1)

传递给事件处理程序的函数,例如 onPress 会丢失其隐式绑定的“this”上下文,当函数被调用时,this 被设置为 undefined。

您有两个选择,您可以使用 bind 方法显式绑定 'this' 的上下文,例如

partitioned_table_2021_01

或者使用箭头函数,将“this”的上下文绑定到函数定义的范围,例如

 <TouchableOpacity style={styles.button} onPress={this.storeData.bind(this)}>
     <Text>Submit</Text>
 </TouchableOpacity>