javascript - 我忘记了如何在 React 中设置初始状态吗? ( react native )

标签 javascript reactjs react-native

因此请考虑以下几点:

import React, { Component } from 'react';

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

class CreateTweet extends Component {

  getInitialState() {
    return {
      text: 'Fake Value'
    }
  }

  render() {
    console.log(this.state);
    return(
      <View style={styles.container}>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 100,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

AppRegistry.registerComponent('CreateTweet', () => CreateTweet);

module.exports = CreateTweet;

运行时状态为null。可以看到console.log(this.state) 我在组件初始化的时候设置状态,这是怎么回事?在 React Native 中是否有一些我不知道的与 React 不同的魔法?

最佳答案

由于您正在使用类,因此您的状态应该在构造函数中设置:

constructor (props) {
  super(props)
  this.state = {
      text: 'Fake Value'
    }
}

关于javascript - 我忘记了如何在 React 中设置初始状态吗? ( react native ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37736354/

相关文章:

javascript - 在 ES6 中从父类调用子方法

javascript - 如何获取可能定义或未定义的表格单元格的 Javascript 集合

react-native - 响应 native 暂停/播放 GIF

typescript - 类型错误 : Cannot read property 'viewManagersNames' of undefined - Integrating Jest and Enzyme with React Native TypeScript Package

javascript - 如何获取所有 optgroup 选项值并将它们推送到数组?

javascript - 如何防止片段标识符显示在 url 中

javascript - react 。使用粗箭头函数声明组件(ES6语法规范)

reactjs - React-router 和漂亮的 URL

reactjs - Redux - 在 TextInput 组件中输入内容后状态无法正确更新

react-native - 如何在 React Native 中将 View 导出为图像数据