React Native中的不变违规:文本字符串必须在<Text>组件内呈现

时间:2020-05-07 08:31:10

标签: react-native

我正在使用REST APis进行React-Native项目,目前我遇到了一个不变的违规错误。我以前曾经经历过,但是我无法完全弄清楚是什么原因以及如何修复它。如果有人能指出正确的方向,我将不胜感激!完整的错误如下图所示,并且似乎在代码中引用了多个标签,因此我不确定它的起源。感谢您的阅读,并预先感谢!

enter image description here

代码在这里:

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>
      );
    }
  }

1 个答案:

答案 0 :(得分:2)

我想你只是有一点错字..

选中此行:<Text>{item.name}</Text>/>

将最后一个文本更改为</Text>