简体   繁体   English

在本机反应中获得太多重新渲染错误

[英]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:我试图显示一个 FlatList,它最初是隐藏的,当用户点击一个 TextInput 时,但我收到一个错误,说有太多的重新渲染,看看代码:

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: :)当我将{setState({showFlatList: true})}放在onFocus上时,我只会收到此错误,但是当我将它放在 TouchableOpacity 内的onPress中时,它起作用了,感谢任何形式的反馈::)

The problem is how you call setState on the onFocus property of your TextInput .问题是如何在TextInputonFocus属性上调用setState

It should look more like this:它应该看起来更像这样:

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

So the same way you handled your TouchableOpacity 's onPress .因此,与您处理TouchableOpacityonPress的方式相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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