this.state在render函数中为null

时间:2018-02-02 18:30:53

标签: javascript android reactjs react-native react-native-android

我在react-native中编写了一些代码,当我在render函数中使用this.state时,它将它显示为一个null对象

import React, { Component } from "react";
import {
  TextInput,
  Text,
  View,
  AppRegistry,
  Image,
  StyleSheet
} from "react-native";
import Greet from "./compo/greet";

export default class App extends Component {
  Constructor(props) {
    Super();
    this.state = {
      test: "nothing to display"
    };
  }

  render() {
    return (
      <View style={styles.view}>
        //here is where error is coming[enter image description here][1]
        <Text> {this.state.test} </Text>
        <TextInput
          style={styles.input}
          keybordType="default"
          placeholder="enter the secret "
        />
      </View>
    );
  }
}

这显示错误 &#34;类型错误null不是一个对象(评估&#39; this.state.test&#39;)&#34; 它只是意味着this.state为null 怎么做

2 个答案:

答案 0 :(得分:1)

小心构造函数和super的字母大小写。

   constructor(props){
      super(props);
      this.state={
        test:"nothing to display"
      };
    }

这应该可行,ES6类构造函数必须调用super,如果它们是子类的话。

答案 1 :(得分:0)

你有套管问题。此外,似乎stylesundefined

import React, { Component } from "react";
import { render } from "react-dom";
import {
    TextInput,
    Text,
    View,
    AppRegistry,
    Image,
    StyleSheet
} from "react-native";
// import Greet from "./compo/greet";

export default class App extends Component {
    constructor(props) {
        super();
        this.state = {
            test: "nothing to display"
        };
        this.styles = {
            view: "display: block;",
            input: "display: block"
        };
    }

    render() {
        return (
            <View style={this.styles.view}>
                <Text> {this.state.test} </Text>
                <TextInput
                    style={this.styles.input}
                    keybordType="default"
                    placeholder="enter the secret "
                />
            </View>
        );
    }
}

render(<App />, document.getElementById("root"));

沙箱:https://codesandbox.io/s/5x12zyyr0l