【发布时间】:2021-06-05 13:42:47
【问题描述】:
我的用户个人资料有以下代码,我对箭头函数的使用有几个问题。
import React, { useContext } from 'react'
import { View, Text, ScrollView } from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { Button } from 'native-base'
import AuthGlobal from '../../Context/store/AuthGlobal'
const UserProfile = (props) => {
const context = useContext(AuthGlobal)
const logoutHandler = (context) => {
AsyncStorage.removeItem('auth')
// call some method using context parameter
}
return (
<ScrollView>
<View
style={{
flexDirection: 'row',
}}
>
<View
style={{
flex: 1,
padding: 10,
}}
>
<Button
onPress={() => logoutHandler(context)}
>
<Text>
Sign Out
</Text>
</Button>
</View>
</View>
</ScrollView>
)
}
export default UserProfile
箭头函数的最佳使用方式是什么?
1.
const logoutHandler = (context) => {
AsyncStorage.removeItem('auth')
// call some method using context parameter
}
<Button
onPress={() => logoutHandler(context)}
>
<Text>
Sign Out
</Text>
</Button>
或 2.
const logoutHandler = (context) => {
AsyncStorage.removeItem('auth')
// call some method using context parameter
}
<Button
onPress={logoutHandler(context)}
>
<Text>
Sign Out
</Text>
</Button>
我尝试了第二个选项,因为箭头函数是浪费的重新渲染 (https://blog.codemagic.io/improve-react-native-app-performance/) Avoid Arrow Functions。但在那种情况下,我会收到这个奇怪的错误 ERROR Warning: Cannot update a component from inside the function body of a different component.
【问题讨论】:
标签: react-native arrow-functions