首页 > 解决方案 > 将箭头函数与 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.

标签: react-nativearrow-functions

解决方案


在情况 2) 中,您实际上并没有给 Button 组件一个函数,而是调用函数 logoutHandler 并将此函数调用的结果提供给 Button。这意味着您的函数 logoutHandler 在加载 JSX 时被调用。

错误可能是由于函数 logoutHandler 在完全呈现 Button 之前导致重新呈现。

为了优化,您可以执行以下操作:

const buttonFunction = () => logoutHandler(context)

并使用 buttonFunction 作为 Button 的值。然后,“功能”将不会重新呈现。从个人经验来看,我只会在代码运行之后进行优化,并且您觉得性能不足以满足您的应用程序


推荐阅读