简体   繁体   中英

React Native FlatList Renders Multiple Times

As I see from many posts that there is a huge problem about FlatList rendering multiple times and causes some problem. Its really annoying and so far I couldnt find any solution for this, and I guess many people have the same situation.

Here is the code, so when I alert instead of seeing one value, I see different values which contains undefined..undefined..real value..undefined . I can also describe it like when I put only 1 element (like {item.message} ) it renders double and makes some spaces between.. like always some strange rendering, so when I add press event on something, I dont get the proper value to alert in press event..

How to solve this flatlist rendering problem??

render(){
        return(
            <View>
                <FlatList
                data={this.state.messages}
                renderItem={({item}) =>

                    <View key={item.id}>

                        <Text> {item.sender} </Text>
                        <TouchableOpacity onPress={() => alert(item.id)} >
                            <Text>{item.message} {item.id}</Text>
                        </TouchableOpacity>

                    </View>

                    }
                />
            </View>
        );
    }

Strange but I solved the problem, and maybe many people have similar problems about flatlist rendering. So problem was caused by backend.

I was creating array in backend before sending to react-native, and there I was doing like this:

 $new = new Collection();

 $new[] = array('message' => $message->message);
 $new[] = array('id' => $message->id);
 $new[] = array('sender' => 'Sender: System');

return $new;

and after I get the array to react-native I was trying to render in flatlist. I noticed that it renders as many as I added new array(), so I fixed the problem by doing:

$new[] = array('message' => $message->message, 'key' => strval($message->id), 'sender' => 'Sender: System');

Hope it can help some other people who was similar codes and problem!..

我不确定,但是(在我的情况下)renderItem似乎将渲染所有项目,并取决于传递给data={this.state.messages}data={this.state.messages}数组中有多少个元素,整个列表将重新呈现再次。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM