react-native - 将箭头函数与 React 本机 JSX 元素一起使用的正确方法是什么
问题描述
我的用户个人资料有以下代码,我对箭头功能的使用几乎没有疑问。
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.
解决方案
在情况 2) 中,您实际上并没有给 Button 组件一个函数,而是调用函数 logoutHandler 并将此函数调用的结果提供给 Button。这意味着您的函数 logoutHandler 在加载 JSX 时被调用。
错误可能是由于函数 logoutHandler 在完全呈现 Button 之前导致重新呈现。
为了优化,您可以执行以下操作:
const buttonFunction = () => logoutHandler(context)
并使用 buttonFunction 作为 Button 的值。然后,“功能”将不会重新呈现。从个人经验来看,我只会在代码运行之后进行优化,并且您觉得性能不足以满足您的应用程序
推荐阅读
- r - 如何将来自两个小标题或数据框的值粘贴到 R 中的组合显示表中?
- php - 如何将 Google 跟踪代码管理器的初始流量源 cookie 值转换为数组?
- c# - 导出 UltraExpandableGroupBox 默认展开指示器
- javascript - 如何区分按钮?
- javascript - 无法返回 res.send 中对象的所有属性
- matlab - Matlab中的稀疏矩阵编码
- google-data-studio - 由于连接器错误,无法提交凭据
- vue.js - 为什么我的 Vue 路由器会抛出最大调用堆栈错误?
- javascript - 有没有办法根据正在使用的浏览器来加载 npm 包?
- google-apps-script - 按日期重新排序 Google Sheet 工作表