【问题标题】:What is the correct way to use Arrow Function with React native JSX element将箭头函数与 React 本机 JSX 元素一起使用的正确方法是什么
【发布时间】: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


    【解决方案1】:

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

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

    为了优化,你可以这样做:

    const buttonFunction = () => logoutHandler(context)
    

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

    【讨论】:

    • 在这种情况下,案例 1 是正确的方法吗?使用案例 1 是否有任何性能缺陷?
    • 是的,案例 1 是正确的方法。请参阅编辑后的答案
    • 好的,谢谢,我使用案例 1 进行了实现,但是正如我在问题中提到的,我看到一篇文章说在渲染器中调用箭头函数会产生性能问题。这就是为什么我尝试了案例 2 并遇到了这个问题。
    • 根据您编辑的答案,这是否意味着像这样通过onPress={buttonFunction} ?
    • 是的,这就是我的想法。然后,buttonFunction 只创建一次,这就是优化您链接的网站背后的想法
    猜你喜欢
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2020-02-08
    • 2018-04-10
    • 2013-01-02
    • 1970-01-01
    • 2020-08-27
    • 2020-07-10
    相关资源
    最近更新 更多