在本机反应中出现太多重新渲染错误

Getting too many re-renders error in react native

当用户单击 TextInput 时,我正在尝试显示一个最初隐藏的 FlatList,但我收到一条错误消息,指出重新呈现的次数过多,请查看代码:

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>
);

当我将 {setState({showFlatList: true})} 放在 onFocus 上时,我只会收到此错误,但是当我将它放在 TouchableOpacity 内的 onPress 内时,它起作用了,任何类型的反馈都是赞赏! :)

问题在于您如何在 TextInputonFocus 属性 上调用 setState

它应该看起来更像这样:

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

因此,与您处理 TouchableOpacityonPress 的方式相同。