首页 > 解决方案 > React Native,限制来自外部文档的 JSON 输出

问题描述

我正在尝试将 JSON 内容输出到一个 Flatlist 中,如 react native 文档中所述。将内容输出到页面不是问题,我正面临着,我试图限制从每个 JSON 字段输出的数据量。

例如,有四种状态,身体、精神、情绪和精神。我试图只输出第一个元素,所以在这种情况下是物理的,或者 [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?"
    }
  ]
 }

标签: androidjsonreact-nativereact-native-flatlist

解决方案


尝试切片数据

 <FlatList
                        data={this.state.dimensionJson.slice(0,1)}
                        renderItem={({item}) => <Text style={[styles.dimensionTitle, { color: progress[3] }]}>{item.type}</Text>}
                        keyExtractor={({id}, index) => id}
                        /> 

推荐阅读