我正在尝试将JSON内容输出到一个套件列表中,如React Native Docs中所述。将内容输出到页面不是问题,我正在面对,我正在尝试限制每个JSON字段输出的数据量。
例如,有4个州,身体,精神,情感和精神。我正在尝试仅输出第一个元素,因此在这种情况下,或[0]。
我有以下代码,该代码将输出所有4个值,并且我在将值限制为仅第一个元素时遇到困难:
<FlatList
data={this.state.dimensionJson}
renderItem={({item}) => <Text style={[styles.dimensionTitle, { color: progress[3] }]}>{item.type}</Text>}
keyExtractor={({id}, index) => id}
/>
检索JSON数据的代码如下:
componentDidMount(){
return fetch(url,{
method: 'GET',
headers: {
Accept: 'applications/json',
},
},
)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
titleData: responseJson.title,
fullJSON: responseJson,
dimensionJson: responseJson.dimensions,
}, function() {
//Potentially write if function in here for limiting output
});
})
.catch((error) =>{
console.error(error)
})}
最后我的JSON看起来像这样:
{
"description": "Begin by identifying the dimension of energy you would like to address. Your scores can guide the way.",
"title": "Choose a Dimension",
"dimensions": [
{
"id": "0",
"type": "Physical",
"desc": "Physical energy is the quantity of energy. This dimension shapes our sustainability and long-term productivity."
},
{
"id": "1",
"type": "Mental",
"desc": "Mental energy is the focus of our energy. It influences our
concentration, control of attention, and the likelihood of making mistakes."
},
{
"id": "2",
"type": "Emotional",
"desc": "Emotional energy is the quality of our energy. It affects how
resilient we are, especially when faced with complexity."
},
{
"id": "3",
"type": "Spiritual",
"desc": "Spiritual energy is the energy we derive from serving a
greater purpose. It inspires us and answers the question ‘Why do I get out
of bed each morning?"
}
]
}
尝试切片数据
<FlatList
data={this.state.dimensionJson.slice(0,1)}
renderItem={({item}) => <Text style={[styles.dimensionTitle, { color: progress[3] }]}>{item.type}</Text>}
keyExtractor={({id}, index) => id}
/>