更改状态后组件未更新

问题描述 投票:3回答:2

在我的应用程序内部,我有一个组件如下:

import React, {Component} from 'react'
import {View, Text, FlatList, TouchableOpacity} from 'react-native'

export default class Screen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selected: null
        }
    }

    renderText(item, index) {
        return (
            <TouchableOpacity
                style={{
                    borderWidth: 1, 
                    borderColor: '#bbbbbb', 
                    backgroundColor: this.state.selected == index ? 'blue' : 'white',
                    marginTop: index == 0 ? 0 : 10
                }}
                onPress={() => {
                    this.setState({selected: index})
                }}
            >
                <Text style={{padding: 10}}>{item.text}</Text>
            </TouchableOpacity>
        )
    }

    renderArray() {
        return (
            <FlatList 
                data={this.props.data}
                renderItem={({item, index}) => this.renderText(item, index)}
                keyExtractor={(item, index) => index.toString()}
            />
        )

    }

    render() {
        return (
            <View style={{margin: 10}}>
                {this.renderArray()}
            </View>
        )
    }
}

如你所见,我正在渲染一个FlatList,对于每个项目,在数组中,Text中有一个TouchableOpacity组件。当您单击每个项目时,this.setState({selected: index})会将selected中的state设置为该项目的索引。 this.state.selectedTouchableOpacity的风格有关,我期望点击一个项目,它的背景变成蓝色,但这没有发生,并且根本没有颜色变化。如果你帮助我,我将不胜感激。

react-native
2个回答
4
投票

原因是FlatList仅在this.props.data更改时重新呈现。你需要“暗示”它还要观察this.state的变化。为此,请在FlatList上设置extraData={this.state}。见https://facebook.github.io/react-native/docs/flatlist


1
投票
      <FlatList 
            data={this.props.data}
            renderItem={({item, index}) => this.renderText(item, index)}
            keyExtractor={(item, index) => index.toString()}
            extraData={this.state}
        />

通过将extraData = {this.state}传递给FlatList,我们确保当state.selected更改时,FlatList本身将重新呈现。如果不设置此prop,FlatList将不知道它需要重新渲染任何项目,因为它也是PureComponent,并且prop比较不会显示任何更改。

© www.soinside.com 2019 - 2024. All rights reserved.