React native setState() 没有按预期重新渲染

React native setState() not re-render as expected

我用react-native-snap-carousel做了一个carousel,下面是carousel的代码。在 carousel 中有 picker 和 textInput 等。 对于渲染函数:

<Carousel
            ref={(c) => { this._carousel = c; }}
            data={this.state.question}
            renderItem={this._renderItem}
            sliderWidth={standard * 1.1}
            itemWidth={standard * 0.9}

            inactiveSlideScale={0.9}
            inactiveSlideOpacity={0.7}

            firstItem={0}

            activeSlideAlignment={'center'}
            containerCustomStyle={styles.slider}
            contentContainerCustomStyle={styles.sliderContentContainer}
              />

细节渲染:

_renderItem ({item, index}) {
  var content;
  switch (item.id) {
      case 1:
          content = <View style={styles.carousel_cell}>
                        <Text style={styles.carouselItemTitle}>{item.displayLabel}</Text>
                        <TextInput style={styles.editor} onChangeText={(text) => this.setState({comment: text})} value={this.state.comment} />
                    </View>;
          break;
      case 2:
          content = <View style={styles.carousel_cell}>
                        <Text style={styles.carouselItemTitle}>{item.displayLabel}</Text>
                        <Picker mode="dropdown"
                        style={styles.picker}
                        selectedValue={this.state.priority}
                        onValueChange={(itemValue) => this.onPriorityChange(itemValue)}>

                          {this.state.list}
                        </Picker>

                    </View>;
          break;
      default:
          content = <View style={styles.carousel_cell}>
                        <Text style={styles.carouselItemTitle}>{item.displayLabel}</Text>
                        <Text>Unknown</Text>
                    </View>;
          break;

  }

  return content;

}

对于事件触发:

onPriorityChange(value) {
    this.setState({priority: value});
}

这里的问题是,在我 select Picker 中的任何项目之后,状态确实得到了更新,但在界面上却没有。一旦触发 onChangeText 事件,就会调用 Picker 的渲染函数。届时 Picker 中的显示也将更新。 但是,根据生命周期,当我设置状态时,轮播(包括它的单元格)不应该是updated/re-rendered吗?

旋转木马中的秒表(来自react-native-stopwatch-timer)也会有同样的问题。

我不知道这个包,但 Carousel 组件似乎继承自 FlatList 组件。

documentation 说:

By passing extraData={this.state} to FlatList we make sure FlatList itself will re-render when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.

因此,请尝试将 extraData={this.state} 添加到您的 Carousel 组件中。