首页 > 解决方案 > 如何在 React Native 中获取子字符串

问题描述

我正在从 Api 获取数据并将其显示在 FlatList 中,但我只想向用户显示有限的字符串,而不是我从 Api 获得的整个文本。

以下是我从服务器获取的示例文本。

 "Text": "Apu Nahasapeemapetilon - Apu Nahasapeemapetilon is a recurring character in the American animated television series The Simpsons." 

在这里,我只想显示数据,直到--不希望在 Flatlist 中显示这么长的数据。有没有办法只在-签名之前获取文本。

下面是我的代码:

import React, {useEffect,useState} from 'react';
import {View,Text,StyleSheet,ActivityIndicator,FlatList} from 'react-native';

const List = () => {

const[post,setPost] = useState([]);
const[isLoading,setLoading] = useState(true);

useEffect(() => {
    
    const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
    fetch(url).then((res) => res.json())
    .then((resp) => setPost(resp.RelatedTopics))
    .catch((err) => alert(err));
 },[]);

    return(

      <View>

            <FlatList 
            data = {post} 
            keyExtractor = {(item) => item.FirstURL} 
            renderItem = {({item}) => <Text>{item.Text}</Text>} />
      
      </View>
    );

};

const styles = StyleSheet.create({
 testStyle:{
     flex: 1,
     justifyContent:"center",
     alignItems:"center"
   }
});

export default List; 

有人让我知道我怎样才能得到想要的结果。

标签: androidreact-native

解决方案


在 flatlist 中显示文本节点时使用 slice 方法

例如 var a = "Apu Nahasapeemapetilon - Apu Nahasapeemapetilon 是美国动画电视连续剧《辛普森一家》中反复出现的角色。"

然后

a.split('-', 1)[0] 将给出“Apu Nahasapeemapetilon”


推荐阅读