【问题标题】:Invariant Violation in React Native: Text strings must be rendered within a <Text> componentReact Native 中的不变违规:文本字符串必须在 <Text> 组件中呈现
【发布时间】:2020-05-07 08:31:10
【问题描述】:

我正在使用 REST API 开发一个 React-Native 项目,我目前遇到了一个不变的违规错误。我以前经历过这种情况,但我不太清楚是什么原因造成的以及如何解决它。如果有人能指出我正确的方向,我将不胜感激!完整的错误如下图所示,并且似乎引用了代码中的许多标签,所以我不确定它的确切来源。感谢您的阅读,在此先感谢您!

代码在这里:

import React, { Component } from 'react'
import { View, Text, Image, StyleSheet, FlatList} from 'react-native';
import * as Font from 'expo-font';
import styled from 'styled-components';
import dimensions from '../components/ScreenSize';
import colours from '../components/Colours';
import { Audio } from 'expo-av';
import { TouchableHighlight } from 'react-native-gesture-handler';

const client_id = {Client_ID}
const client_secret = {Client_Secret}

const item = ({item}) => (
    <View style={{ flex:1, flexDirection: 'column', margin:1}}>
        <TouchableHighlight onPress={() => this.fetchTracks(item.id)}>
            <View>
                <Text>{item.name}</Text>/>
            </View>
        </TouchableHighlight>
    </View>
)

export default class HomeScreen extends React.Component {
    state={
      fontsLoaded:false,
    }
    async componentDidMount() {
      await Font.loadAsync({
        'montserrat-regular': require('../assets/fonts/Montserrat/Montserrat-Regular.ttf'),
        'montserrat-light': require('../assets/fonts/Montserrat/Montserrat-Light.ttf'),
        'montserrat-semibold': require('../assets/fonts/Montserrat/Montserrat-SemiBold.ttf'),
        'montserrat-bold': require('../assets/fonts/Montserrat/Montserrat-Bold.ttf'),
      }
      ).then(() => this.setState({ fontsLoaded:true }))
      this.getToken();
      this.setAudio();

    }

    constructor (props) {
        super(props)
        this.playbackInstance=null;
        this.state = {
            playing:false,
            token: '',
            DATA:[],
        };
    }

    setAudio=() => {
        Audio.setAudioModeAsync({
            allowsRecordingIOS:false,
            interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
            playsInSilentModeIOS: true,
            shouldDuckAndroid: true,
            interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX,
            playThroughEarpieceAndroid: false,
        });
    }

    componentDidCatch(error, info)
    {
        console.log(error, info.componentStack);
    }

    getToken = async() =>
    {
        try
        {
            const getspotifytoken = await fetch("https://accounts.spotify.com/api/token",
            {
                method:'POST',
                body: `grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}`,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });

            const spotifytoken = await getspotifytoken.json();
            this.setState({
                token: spotifytoken.access_token
            });

            console.log(this.state.token);
        }
        catch(err)
        {
            console.log("Error fetching data", err);
        }
    }

    search = async () => {
        try
        {
            console.log("Searching: mood")
            const spotifyApiCall = await fetch(`https://api.spotify.com/v1/browse/categories/mood/playlists?`, {
                headers: {
                    Accept: 'application/json',
                    Authorization: `Bearer ${this.state.token}`,
                    "Content-Type":'application/json'
                }
            })
            const spotify = await spotifyApiCall.json();
            console.log("Items", spotify);

            this.setState({
                DATA: spotify.playlists.items,
            })
        }
        catch (err)
        {
            console.log("Error fetching data", err);
        }
    }

    fetchTracks = async (playlistId) => {
        console.log('Playlist ', playlistId)
        try
        {
            const getplaylist = await fetch(`https://api.spotify.com/v1.playlist/${playlistId}`,
            {
                method:'GET',
                headers: {
                    Accept:"application/json",
                    Authorization:`Bearer ${this.state.token}`,
                    "Content-Type":"application/json"
                }
            });

            const playlist = await getplaylist.json();
            console.log('music ', playlist.tracks.items[0].preview_url);
        }

        catch (err)
        {
            console.log("Error fetching data ", err);
        }
    }

    async _loadNewPlaybackInstance(playing, track) {
        if(this.playbackInstance != null)
        {
            await this.playbackInstance.unloadAsync();
            this.playbackInstance.setOnPlaybackStatusUpdate(null);
            this.playbackInstance = null;
        }

        const source = {uri: track};
        const initialStatus = {
            shouldPlay: true,
            rate: 1.0,
            shouldCorrectPitch: true,
            volume: 1.0,
            isMuted: false
        };
        const {sound, status} = await Audio.Sound.createAsync(
            source.initialStatus);
            this.playbackInstance=sound;
            this.playbackInstance.setIsLoopingAsync(false);
            this.playbackInstance.playAsync();

        if (this.state.selected === playlistId) {
            console.log("Playing, so stop");
            this.setState({selected:null});
            this.playbackInstance.pauseAsync();
            return;
        }

        this.setState({ selected:playlistId});
        this._loadNewPlaybackInstance(true, playlist.tracks.items[0].preview_url);
    }

    render() { 
      if(!this.state.fontsLoaded ) {
        return null
      }
      return (
        <Container>
          <Titlebar>
            <Title>Music</Title>
          </Titlebar>
          <HeaderBar2>
            <TouchableHighlight onPress={() => this.search()}> 
              <Header2>Playlists for your Mood</Header2>
            </TouchableHighlight>
          </HeaderBar2>
          <View style={styles.MainContainer}>
          {
                this.state.DATA.length == 0 &&
                <Text style={{padding:10, color:'#D3D3D3'}}/>
              }
              <FlatList
              data = {this.state.DATA}
              renderItem={item}
              keyExtractor = {item.id}
              numColumns={2}
              extraData = {this.state}
              />
          </View>
        </Container>
      );
    }
  }

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我想你只是有一个小错字..

    检查这一行:&lt;Text&gt;{item.name}&lt;/Text&gt;/&gt;

    将最后一个Text改为&lt;/Text&gt;

    【讨论】:

    • 谢谢,我没注意!虽然看起来我获取的数据没有呈现在屏幕上;你知道这是为什么吗?
    猜你喜欢
    • 2020-08-19
    • 2020-01-20
    • 2019-02-21
    • 2019-06-27
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多