更新扩展组件的 class 中的渲染

Update render in class that extends component

如何在扩展组件时更新 React Native class 的渲染?

我尝试使用在 "first screen class" 和 menu/navigator class 中工作的 setState 作为应用程序的 shell,但是当我尝试在从 shell 调用的另一个 class 中使用此函数我收到错误消息 "Warning: getInitialState was defined on..., a plain javascript class..." 并且在尝试使用 setState 或 forceUpdate 消息“警告 forceUpdate/setState (等等on) 只能更新一个已挂载或安装的组件。

有代码重新渲染的解决方案吗?

import React, { Component, PropTypes } from 'react';
import { View, Text, TouchableHighlight } from 'react-native';

export default class testClass extends React.Component {

    constructor(props) {
            super(props)
        }

    getInitialState() {
            return {
                isLoading: true,
                PackageNo: '',
                PackageNoSeq: '',
                hasError: false,
                errorMessage: '',
            };
        }

  render() {
    return (
      <View>
        <Text>Test</Text>
        <TouchableHighlight onPress={this.go.bind(this)}>
          <Text>Go to Apple</Text>
        </TouchableHighlight>
      </View>
    )
  }

  go() {
    console.log("go to other");
    this.props.navigator.push({ screen: 'OtherTest' });
  }
}

简单突出显示。 React.createClass 是 React 中 declare/create 组件 class 的传统方式。 getInitialStateReact.createClass 生命周期方法之一,React 团队刚刚发布了一个小的语法糖更新,以允许 extends React.Component 更好地使用 ES6 模块,它扩展了组件 class而不是调用 createClass.

getInitialState 函数已失效,现在您需要在构造函数中将所有状态声明为简单初始化属性

 constructor(props) {
      super(props);
      this.state = {
          isLoading: true,
          PackageNo: '',
          PackageNoSeq: '',
          hasError: false,
          errorMessage: ''
      }
  }

只需使用setState方法重新渲染。或者从父组件传props。

    import React, { Component, PropTypes } from 'react';
    import { View, Text, TouchableHighlight } from 'react-native';

    export default class testClass extends Component {
      state = {
        text: 'Go to Apple'
      }

      onPress = () => {
        this.setState({text: 'Go to hell'})
      }

      render() {
        return (
          <View>
            <Text>Test</Text>
            <TouchableHighlight onPress={this.onPress}>
              <Text>{this.state.text}</Text>
            </TouchableHighlight>
          </View>
        )
      }
    }