【问题标题】:how can i dispatch data rigth after get data?如何在获取数据后立即发送数据?
【发布时间】:2021-04-09 07:24:11
【问题描述】:

如果我采取行动 onPress={() => kakaoLosing()

我想通过使用异步等待从 getProfile 获取数据(这是配置文件)

在将数据发送到 KAKAOLOG_IN_REQUEST 之后,

这是我的代码

            import {
            getProfile as getKakaoProfile,
            } from '@react-native-seoul/kakao-login';


            const Vieww = ({}) => {
            
            const kakaoLosing = useCallback(() => {
                
                const getProfile = async () => {
                const profile = await getKakaoProfile();
                };

                dispatch({
                type:KAKAOLOG_IN_REQUEST,
                data:profile
                })
            },[]);

                return (

                    <Button1 onPress={() => kakaoLosing()} >
                    <Label>
                    profile
                    </Label>
                    </Button1>

但如果我使用此代码

发生了这个错误

        ReferenceError: Can't find variable: profile

如何修复我的代码??

【问题讨论】:

  • 你为什么使用 useCallback 代替普通的箭头函数?有什么目的吗?
  • 您已经在getProfile 函数范围内关闭了profile,它在useCallback 挂钩回调中不可用。然后你也不要打电话给getProfile 来提出请求。
  • 我在您的回调中没有看到 async 关键字
  • 请看看我的回答,也许它会帮助你:)

标签: javascript node.js reactjs react-native


【解决方案1】:

您已经在 getProfile 函数范围内关闭了 profile,它在 useCallback 挂钩回调中不可用。然后你也不要打电话给getProfile 来提出请求。

我认为不需要useCallback 挂钩。只需声明一个普通的async 函数并等待响应。现在profiledispatch 在同一范围内。

const Vieww = ({}) => {
  const kakaoLosing = async () => {
    const profile = await getKakaoProfile();

    dispatch({
      type: KAKAOLOG_IN_REQUEST,
      data: profile
    });
  };

  return (
    <Button1 onPress={kakaoLosing} >
      <Label>
        profile
      </Label>
    </Button1>
    ...

【讨论】:

    【解决方案2】:

    如果你想在单独的函数中这样做,你可以这样做:

        const Vieww = ({}) => {
            const profile = async () => {
              const data = await getKakaoProfile();
              return data;
            }
    
            const kakaoLosng = () => {
              const dataToDispatch = profile();
              
              dispatch({
                type: KAKAOLOG_IN_REQUEST,
                data: dataToDispatch 
                })
            }
            
    

    甚至更简单:

            const Vieww = ({}) => {
                const kakaoLosng = async () => {
                  const dataToDispatch =  await getKakaoProfile();
                  
                  dispatch({
                    type: KAKAOLOG_IN_REQUEST,
                    data: dataToDispatch 
                    })
                }
    

    在按钮上你可以通过:

    return (
        <Button1 onPress={kakaoLosing}>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      • 2016-10-25
      • 2011-11-07
      • 1970-01-01
      相关资源
      最近更新 更多