我有这个React Native代码:
import React, { Component } from 'react';
import { ScrollView, StyleSheet, TouchableHighlight, View, Text, Platform } from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
export default class MyList extends Component {
constructor(props) {
super(props);
this.state = {autoPlay: true, width: 0};
this._onScroll = this._onScroll.bind(this);
this._goToNextPage = this._goToNextPage.bind(this);
this._startAutoPlay = this._startAutoPlay.bind(this);
this._stopAutoPlay = this._stopAutoPlay.bind(this);
this._myIndex = 0;
}
render() {
console.log("In render, this.state: " + JSON.stringify(this.state));
console.log("In render, this._myIndex: " + this._myIndex);
//some other code
}
}
打印:
ReactNativeJS: In render, this.state: {"autoPlay":true}
ReactNativeJS: In render, this._myIndex: 0
为什么this.state
仅部分初始化constructor
?
状态应设置为{autoPlay: true, width: 0}
,但仅设置为{"autoPlay":true}
。
我知道constructor
正确地初始化了其他变量,例如this._myIndex
,因为如果我更改了我在构造函数中给出的值,那么它将显示在日志中。
但是,this.state
未在构造函数中正确初始化。为什么呢?