【问题标题】:ListItem not rerendering in FlatList when observable array changes当可观察数组更改时,ListItem 不会在 FlatList 中重新呈现
【发布时间】:2019-02-22 12:37:36
【问题描述】:

我有一个名为 CheckListItem 的组件,其中包含:

<ListItem
    leftAvatar={this.props.leftAvatar}
    title={this.props.title}
    leftIcon={this.state.icon}
       onPress={(event) => {
          this.props.onSelect();
       }}
    containerStyle={{ backgroundColor: this.state.color }}
    switch={{ value: this.props.isSelected, disabled: true }} // <-- this switch
/>

我将它作为观察者导出:

export default (observer(CheckListItem));

并从我所谓的 CountryPage 中使用它:

render() {
    console.log(toJS(this.props.store.countries)); // <-- prints the expected updated list
    return (
        <View style={{ flex: 1 }}>
            <Text>{this.state.ouputText}</Text>
            <FlatList
                data={this.props.store.countries}
                renderItem={({ item }) =>
                    <CheckListItem
                    title={item.name}
                    leftAvatar={{ source: { uri: item.flag } }}
                    onSelect={() => { SearchParameters.getInstance().setCountrySelected(item.key); }}
                    isSelected={item.isSelected} //<-- won't update
                    />
                }
            />
        </View>
    );
}

我注入了我的商店,它是 SearchParameters 的单例实例

export default inject('store')(observer(CountryPage));

每当我获得我的 SearchParameters 实例并更改驻留在那里的列表 (isSelected) 中的任何属性时。 CountryPage 重新呈现并记录预期的更新列表。我的问题是这不会更新 CheckListItem - 并重新渲染它。每当列表元素更改和重新呈现时,如何让我的 CheckListItem 组件接收更新的道具?

【问题讨论】:

    标签: react-native mobx listitem react-native-flatlist


    【解决方案1】:

    我发现我的答案是这里的第二个答案:React Native mobx binding to FlatList not working。在 CheckListItem 周围添加 Observer 使得“isSelected”被向下传递,从而更新了开关。

    render() {
        console.log(toJS(this.props.store.countries));
        return (
            <View style={{ flex: 1 }}>
                <Text>{this.state.ouputText}</Text>
                <FlatList
                    data={this.props.store.countries}
                    renderItem={({ item }) =>
                        <Observer>
                            {() => 
                            <CheckListItem
                            title={item.name}
                            leftAvatar={{ source: { uri: item.flag } }}
                            onSelect={() => { SearchParameters.getInstance().setCountrySelected(item.key); }}
                            isSelected={item.isSelected}
                            />
                            }
                        </Observer>
                        }
                />
            </View>
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2016-11-12
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2021-03-25
      相关资源
      最近更新 更多