【发布时间】:2019-03-13 16:45:16
【问题描述】:
我正在尝试将 JSON 内容输出到 Flatlist 中,如 react native 文档中所述。将内容输出到页面不是问题,我正面临着,我试图限制从每个 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?"
}
]
}
【问题讨论】:
-
{item.type} 输出什么?哪个状态元素持有该 json 数据?
-
@soldfor 我想你已经把我引向了问题的原因,我可能需要在状态内创建一个数组来保存数据,然后像普通数组一样解析数据。不完全确定它会起作用,但我今天要试一试
-
没错。当你得到你的回应时,将回应存储在一个状态中。然后,映射该数组
标签: android json react-native react-native-flatlist