首页 > 解决方案 > 如何从 json 服务器正确显示 JSON 数据

问题描述

对于具有多个级别的 JSON 文件,这是呈现它们的正确方法吗?

{
newData: [
  {
    "Company_id" : "1",
    "logo":"Bentley",
    "EmployeeData":[
        {
        "id" : "3",
        "name":"James",
        "age" :"40",      
    },  
       {
       "id": "2"
        "name":"Thomas",
        "age" :"40", 
      }
    ]
  },
 {
    "Company_id" : "2",
    "logo":"Super_cars",
    "EmployeeData":[
        {
        "id" : "9",
        "name":"frank",
        "age" :"50",      
    },  
       {
       "id": "8"
        "name":"Jennie",
        "age" :"80", 
      }
    ]
 }]}

鉴于此 Json 文件托管在模拟 json 服务器上

componentDidMount() {  //retrieving data from json server 
    fetch(newData)
    .then(response => response.json())
    .then((resJson) =>{
        data.filter( x => x.Company_id === 1)
        {
            this.setState({
                data:resJson
            }
        })
        .catch(err => {  
          console.log("Error loading data" + err);
        });        
    }

renderItem =({item}) =>{
      return(
       <View><Text> {item.name}<Text></View>)}

render() {    
 <FlatList
     data={finalDataToDisplay}
     renderItem={renderItem}
     keyExtractor={item => Company.id}
 />
}

这个显示器什么都没有显示,可能是什么原因?也没有错误消息,所以不确定哪里出错了。console.log 似乎包含数据。有人可以指导一下吗,谢谢

标签: jsonreact-nativeformatrenderingdisplay

解决方案


不,你不要那样使用fetch

你可以像这样使用它fetch(URL)// URL -> http://someURL.com/file.json

由于这是本地文件,您可以像这样使用它:

import data from 'yourFile.json'


const func = () => {
  // do whatever you want with the file

  const renderItem = ({item}) => item.name; // also fix this as well, I belive you don't need the const in class Components

  <FlatList data={data} renderItem={renderItem} keyExtractor={item => Company.id} />
}

export default func;

推荐阅读