【问题标题】:Undefined is not an object (evaluating 'this. state.input')未定义不是对象(评估“this.state.input”)
【发布时间】:2017-01-16 13:47:41
【问题描述】:

我正在尝试从 json 文件中读取密钥并在文本字段中显示其值。用户将在 TextInput 字段中输入键值。以下是我使用的代码。输入文本并按下提交按钮后,它会抛出“未定义不是对象(评估'this.state.input')”错误。我认为将值绑定/传递给 showMeaning() 函数存在一些问题。请帮忙。

import React, {Component} from 'react';
import {AppRegistry, StyleSheet, Text, TextInput, View} from 'react-native';

var english_german = 'english_german.json';
class Dictionary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      output: ''
    };
  }

  showMeaning() {
    var meaning = this.state.input in english_german ? english_german[this.state.input] : "Not Found";
    this.setState({
      output: meaning
    });
  }

  render() {
    return (
      <View style={styles.parent}>
        <Text>
          Type something in English:
        </Text>
        <TextInput value={this.state.input}
          onChangeText={(input) => this.setState({ input }) }
          onSubmitEditing = {this.showMeaning}
          />
        <Text style={styles.germanLabel}>
          Its German equivalent is:
        </Text>
        <Text style={styles.germanWord}>
          {this.state.output}
        </Text>
      </View>
    );
  }
};

var styles = StyleSheet.create({
  parent: {
    padding: 16
  },
  germanLabel: {
    marginTop: 20,
    fontWeight: 'bold'
  },
  germanWord: {
    marginTop: 15,
    fontSize: 30,
    fontStyle: 'italic'
  }
});

AppRegistry.registerComponent('Dictionary', function () {
  return Dictionary;
})

【问题讨论】:

  • var english_german = 'english_german.json'; var english_german 必须是文件的内容,而不是名称本身。
  • @leo 如何导入json文件的内容?我尝试了 require() 以及 import from。两者都抛出了模块不可用的错误消息。

标签: javascript reactjs react-native react-redux reactjs-flux


【解决方案1】:

正如 madox2 所说,showMeaning 未正确绑定到 this。这是一个棘手的问题,有几种可能的解决方案,this medium post 列出了它们的优缺点。我认为最简洁的是选项 5,但这需要使用阶段 2 功能。

【讨论】:

    【解决方案2】:

    当您调用 showMeaning 时,它未绑定到正确的上下文 (this)。你应该bind它或使用具有词法this的箭头函数,例如:

    onSubmitEditing = {() => this.showMeaning()}
    

    【讨论】:

    • 或将其添加到您的构造函数中this.showMeaning = this.showMeaning.bind(this)。感觉这已经被说了百万次了:D 看看facebook.github.io/react/docs/reusable-components.html
    • 感谢您的回复。现在它不显示出价错误消息。但是,看起来内容并未从 json 加载。如何导入 json 文件的内容?我试过 require() 以及'import * from *'。两者都抛出了模块不可用的错误消息。
    猜你喜欢
    • 2017-11-05
    • 2016-12-04
    • 2019-09-26
    • 2019-12-12
    • 2019-08-16
    • 2020-08-06
    • 2020-01-09
    • 2017-05-03
    • 2023-03-07
    相关资源
    最近更新 更多