简体   繁体   中英

Getting too many re-renders error in react native

I'm trying to show a FlatList, which is initially hidden, when the user clicks on a TextInput, but I'm getting an error saying that there are too many re-renders, take a look at the code:

const [state, setState] = useState ({
    ...
    showFlatList: false,
})

return (
    <ImageBackground source = {enterInfoBackGroundImage} style = {styles.container}>
        <SafeAreaView>
            <View style = {styles.backgroundArea}>

                <TextInput style = {styles.inputText} 
                    onFocus = {setState({showFlatList: true})}
                    autoCapitalize='characters'
                    placeholder = {'MAKE'}
                    placeholderTextColor = {'#B2B2B2'}
                    onChangeText = {text => setState({...state, companyName: text })}
                    value = {state.make}
                />

                {state.showFlatList && <FlatList
                    style = {styles.tableView}
                    data = {make}
                    keyExtractor = {(item) => item.id}
        
                    renderItem = {({ item }) => (
                        <TouchableOpacity style = {styles.tableViewItem} onPress = {() => {
                            console.log(item.make, item.id)
                        }}>
                
                            <Text style = {styles.searchBarText}>{item.make}</Text>
                        </TouchableOpacity>
                    )}
                />}
            </View>
        </SafeAreaView>
    </ImageBackground>
);

I'm only getting this error when I put {setState({showFlatList: true})} on onFocus , but when I put that inside onPress inside the TouchableOpacity, it worked, any kind of feedback is appreciated: :)

The problem is how you call setState on the onFocus property of your TextInput .

It should look more like this:

<TextInput
  onFocus={() => {
    setState({showFlatList: true});
  }}
  // ...
/>

So the same way you handled your TouchableOpacity 's onPress .

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