【问题标题】:How can I authenticate Spotify in a React Native component?如何在 React Native 组件中验证 Spotify?
【发布时间】:2021-05-09 21:22:18
【问题描述】:

我正在为一个学校项目创建一个 React Native 移动应用程序,我希望用户能够登录到 Spotify,以便能够使用 Spotify API 获取有关其播放的信息。

我正在为 iOS 开发并使用 Expo,所以发现 this documentation from Expo 很有帮助。使用他们的示例 Auth Code,我成功地制作了一个非常简单的 React 应用程序,它允许用户按下一个按钮,提示他们使用 Spotify 登录。但是,对于我的项目,我有不同的组件对应于我的应用程序中的不同屏幕。每当我尝试将代码移动到组件中时,都会收到一个我不确定如何解决的错误(我对 React 和 Javascript 还是很陌生)。

代码如下:

import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { View, Button, StyleSheet } from 'react-native';
import { LoginContext } from '../LoginContext';

WebBrowser.maybeCompleteAuthSession();

// Endpoint
const discovery = {
  authorizationEndpoint: 'https://accounts.spotify.com/authorize',
  tokenEndpoint: 'https://accounts.spotify.com/api/token',
};

const [request, response, promptAsync] = useAuthRequest(
    {
    clientId: CLIENT_ID,
    scopes: ['user-read-email', 'playlist-modify-public'],
    // In order to follow the "Authorization Code Flow" to fetch token after authorizationEndpoint
    // this must be set to false
    usePKCE: false,
    redirectUri: 'exp://localhost:19000/--/',
    },
    discovery
);

React.useEffect(() => {
    if (response?.type === 'success') {
    const { code } = response.params;
    }
}, [response]);


export default class Settings extends React.Component {

    render () {

        return (
            <View style={{flex: 1, display: 'flex', justifyContent: 'center', alignItems: "center", alignContent: 'center'}}>  
            <Button
            //disabled={!request}
            title="Login to Spotify"
            onPress={() => {
                //console.log("Login attempt");
                promptAsync();
                }}
            />
            </View>
        );
    }
}

我收到一条错误消息,指出:

错误:无效的挂钩调用。钩子只能在体内调用 的一个功能组件。这可能发生在以下情况之一 原因:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 请参阅https://reactjs.org/warnings/invalid-hook-call-warning.html 以获取有关如何调试和 解决这个问题。

我查看了错误消息中的链接,看看我是否可以调试自己,但我遇到了一些麻烦,因为我对 React 还是很陌生。任何帮助将不胜感激!

【问题讨论】:

    标签: react-native authentication oauth react-hooks expo


    【解决方案1】:

    useAuthRequestuseEffect 就是我们所说的 React 钩子。它们只能用于功能组件。在我看来,你应该首先查看如何在 React 中使用钩子的文档:https://reactjs.org/docs/hooks-intro.html

    
    WebBrowser.maybeCompleteAuthSession();
    
    // Endpoint
    const discovery = {
      authorizationEndpoint: 'https://accounts.spotify.com/authorize',
      tokenEndpoint: 'https://accounts.spotify.com/api/token',
    };
    
    // This is the functional component
    const Settings = () => {
        const [request, response, promptAsync] = useAuthRequest({
          clientId: CLIENT_ID,
          scopes: ['user-read-email', 'playlist-modify-public'],
          // In order to follow the "Authorization Code Flow" to fetch token after authorizationEndpoint
          // this must be set to false
          usePKCE: false,
          redirectUri: 'exp://localhost:19000/--/',
        }, discovery);
    
        React.useEffect(() => {
          if (response?.type === 'success') {
          const { code } = response.params;
          }
        }, [response]);
       
        return (
            <View>...</View>
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 2017-09-16
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多