首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React Native -尽管已定义,但this.state仍未定义?

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

Stack Overflow用户
提问于 2021-05-17 23:30:36
回答 1查看 26关注 0票数 1

在一个应用程序上工作,用户可以输入标题,他们的名字和段落来提交一个故事,然后存储在Firestore数据库中。然而,尽管我输入了一些文本,但当我按下submit按钮调用storeData()时,console.log(firebase.firestore.collection('story'))是"object Object“,而console.log(this.state)是"undefined",尽管我已经在构造函数中清楚地定义了它。

代码语言:javascript
复制
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>
    );
  }
}```
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-17 23:41:06

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

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

代码语言:javascript
复制
 <TouchableOpacity style={styles.button} onPress={this.storeData.bind(this)}>
     <Text>Submit</Text>
 </TouchableOpacity>

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

代码语言:javascript
复制
// 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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67572713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档