React Native:onPress() 在组件渲染时被无限调用,当我按下图标时无法正常工作



下面是我的一些代码。似乎我的组件是无限渲染,图标上的onPress()函数每次渲染时都被调用,但当我实际单击JSX元素时不起作用。我试过用这个绑定函数,正如在类似的帖子中建议的那样,似乎不起作用。

function SearchScreen({ navigation }) {
const [text, setText] = useState('')
const [users, setUsers] = useState([])
const fetchData = (category) => {
fetch("https://stonernautz.com/companies.json")
.then(response => {
return response.json()
})
.then(data => {
setUsers(data)
})
}
const storeData = async (value) => {    
try {
await AsyncStorage.setItem('searchText', value)
getData()
} catch (e) {
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem('searchText')
setText(value)
if(value !== null) {
}
} catch(e) {
}
}

fetchData()
const txtHandler = (enteredName) => {
setText(enteredName);
};
const btnHandler = (icon) => {
console.log(icon)
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"black",color:"white"}}>
<Text style={{position:"absolute", top:50, left:90,fontSize:20, color:'white'}}>Search</Text>
<Ionicons name="location" color={'white'} size={26} style={{position:"absolute", top:50, left:490,fontSize:20}}/>
<TextInput
style={{
backgroundColor:"white",
height: 40,
margin: 12,
borderWidth: 1,
borderBottomColor: '#ffffff',
borderTopColor: '#ffffff',
borderRightColor: '#ffffff',
borderLeftColor: '#ffffff',
padding: 10,
borderColor: "#ffffff",
width:"70%",
position:"absolute",
top:80,
borderRadius:10
}}
placeholder="Search HUB Businesses..."
onChangeText={txtHandler}
defaultValue={text}
></TextInput>
<View style={styles.scrollView}>
<ScrollView style={styles.scrollView} horizontal={true}>
<View style={styles.catView}>
<Ionicons name="cafe" color={'white'} size={26} style={{marginLeft:0, marginTop:10}}/>
<Text style={{color:"white"}}>Cafe</Text>
</View>
<View style={styles.catView}>
<Ionicons name="pizza" color={'white'} size={26} style={{marginLeft:0, marginTop:10}} onPress={this.storeData.bind(this,'pizza')}/>
<Text style={{color:"white"}}>Pizza</Text>
</View>
<View style={styles.catView}>
<Ionicons name="paper-plane" color={'white'} size={26} style={{marginLeft:0, marginTop:10}} onPress={this.storeData.bind(this,'travel')}/>
<Text style={{color:"white"}}>Travel</Text>
</View>
<View style={styles.catView} onPress={btnHandler}>
<FontAwesome name="tree" color={'white'} size={26} style={{marginLeft:0, marginTop:10}}  onPress={this.storeData.bind(this,'tree')}/>
<Text style={{color:"white"}} >Tree</Text>
</View>

你不应该在onPress中调用函数,你应该传递函数。

交货。changeonPress={this.storeData.bind(this,'travel')}

:

onPress={ () => storeData('travel')}

最新更新