android - 如何在 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;
有人让我知道我怎样才能得到想要的结果。
解决方案
在 flatlist 中显示文本节点时使用 slice 方法
例如 var a = "Apu Nahasapeemapetilon - Apu Nahasapeemapetilon 是美国动画电视连续剧《辛普森一家》中反复出现的角色。"
然后
a.split('-', 1)[0] 将给出“Apu Nahasapeemapetilon”
推荐阅读
- delphi - Datasnap 会话已过期
- ios - 如何在 ios ionic build 中解决“'FIRInstanceID' 没有可见的@interface 声明选择器'token'”
- html - 我的本地 Html Ref 由于某种原因无法正常工作
- single-sign-on - SSO 在不同浏览器中的工作功能
- python - 使用 ColumTransformer/FeatureUnion 后构建完整数据框(特征值 + 名称)的推荐方法是什么?
- javascript - 带有 Laravel 和 Vue.js v-model 问题的待办事项列表
- apache-kafka - 从 kafka 流中读取 peek 主题
- javascript - 使用 react-bootstrap 或 material-ui 反应复选框状态管理?
- typescript - 如何将元素添加到数组中的json数组?
- java - MyBatis 生成器包括视图