[RN] react-native FlatList 实现列表选中的最佳方式(刷新指定Item)

效果如下:

核心思路就是往数据源里面 给每条数据加一个选中状态.

如图在网络请求完成之后,给每条数据添加一个select的状态:

data.list.forEach(item => item.select = false);

fetchList(page) {
        if (page == 1 && !this.state.refreshing) {
            Toast.loading('加载中', 0)
        }
        Fetch.postFetch(API.homeList, { page }).then(data => {
            // 这一句是核心代码
            data.list.forEach(item => item.select = false);
            if (1 == page) {
                this.setState({
                    listData : data.list,
                    total : data.info.total,
                    page : page + 1,
                    refreshing : false,
                }, () => Toast.hide())
            } else {
                const oldData = this.state.listData;
                this.setState({
                    listData : oldData.concat(data.list),
                    total : data.info.total,
                    page : page + 1,
                    loadingMore : false,
                }, () => Toast.hide());
            }
        })
    };

然后就是render FlatList

<FlatList
    style={styles.flatList}
    data={listData}
    // 这是一种数据源没有唯一id的时候自己手动生成的方式 +"1" 是为了把int类型转string 因为key是需要string类型
    // keyExtractor={(item, index) => (index + '1')}
    keyExtractor={item => item.id}
    renderItem={({ item, index }) => (
        <Item
            item={item}
            select={item.select}
            onPress={() => this.changeSelect(index, item.select)}
        />)
    }
/>

然后就是 Item 里面 需要做渲染更新判断了,shouldComponentUpdate是指定渲染的关键

扫描二维码关注公众号,回复: 6819938 查看本文章
export default class Item extends Component {

    shouldComponentUpdate(nextProps,nextState){
        return (this.props.item != nextProps.item || this.props.select != nextProps.select);
    }

    render() {
        // 这里我就把其他布局文件省略了
        console.log('item render ')  // 从这里可以看到 每次改变item是,只刷新了指定item
        const { item } = this.props;
            return (
                <TouchableOpacity style={styles.container} onPress={this.props.onPress}>
                    {
                        item.select ?
                            <Icon name='oneIcon|icon_check_fill' size={FS.ICON} color={CS.THEME11}/>
                            :
                            <Icon name='oneIcon|icon_checkBox' size={FS.ICON} color={CS.THEME11}/>
                    }
                </TouchableOpacity>
            );
    }
}

这里更建议用这种写法,简洁(ES6的写法 字符串模板)

<Icon name={`oneIcon|${item.select? 'icon_check_fill':'icon_checkBox' }`} size={FS.ICON} color={CS.THEME11}/>

参考来源:

https://www.jianshu.com/p/437a195e4f14

猜你喜欢

转载自www.cnblogs.com/wukong1688/p/11209497.html
今日推荐