首页 > 解决方案 > Image fliker once 使用 setState() 更新图像列表

问题描述

我有每个元素的图像 url 和 otehr 参数的列表。现在我在每个元素“isFavorite”(真/假)中添加了更多参数,默认设置为“假”。

现在我单击图像调用最喜欢/不喜欢的 api 并在 API 上成功,更新列表,如 isFavorite: true ,如果为 true 则为特定元素设置为 false 。

所以,现在的问题是,一旦我设置了最喜欢/不喜欢的标志并使用 setState() 更新我的列表,图像就会闪烁或闪烁。

听到图片网址未更改。

我还检查了“KeyExtracter”键对于所有元素都是唯一的,并且列表更新后键不会更改。

我还设置了图像属性的源和默认源,但仍然图像会更漂亮。

请检查以下代码

            <FlatList
                ref={(ref) => { this.flatListRef = ref; }}
                data={this.state.articles}
                renderItem={({ item }) => (<Article
                    navigation={this.props.navigation}
                    isMemberLoggedIn={this.state.isMemberLoggedIn}
                    article={item}
                    addFavoriteCallBack={() => this.onPressAddFavoriteArticles(item.id)}
                    removeFavoriteCallBack={() => this.onPressRemoveFavoriteArticles(item.id)}
                />)}    
                keyExtractor={(item, index) => index.toString()}
                ------
            />

         
         // Add favorite
         if (response) {
            let tempArticles = this.state.articles.map((ele, i) => {
                if (ele.id === articleId) {
                    ele.isFavorite = true;
                }
                return ele;
            })
            this.setState({ articles: tempArticles });
        }

       
        // Remove favorite
         if (response) {
            let tempArticles = this.state.articles.map((ele, i) => {
                if (ele.id === articleId) {
                    ele.isFavorite = false;
                }
                return ele;
            })
            this.setState({ articles: tempArticles });
        }

如果有人有解决方案或其他任何事情,请提供帮助。

提前致谢。

标签: reactjsreact-native

解决方案


尝试使用 React.memo 或 useMemo react hook 创建自定义组件,它可以帮助您重新渲染和返回 memoized 组件。

看看下面的例子。

反应备忘录示例


推荐阅读