首页 > 解决方案 > 循环遍历对象并以本机反应显示数据

问题描述

我正在尝试从 api 中提取数据并将其显示给用户。我已经进行了成功的 fetch 调用,并且正在我的 HomeScreen 组件中循环浏览数据。

  const HomeScreen = ({navigation}) => {

  const [showData, setShowData] = useState();

  const [show, setShow] = useState('Car');
  

  const getShow = () => { 
    fetch('http://api.tvmaze.com/search/shows?q='+show)
    .then((response)=> response.json())
    .then((json)=>{

      for (let i = 0; i < json.length; i++) {
        
      setShowData({
        name: json[i].show.name,
        desc: json[i].show.summary,
        image: json[i].show.image,
      });
    }
      })
    
      .catch((error)=>{
          console.log(error);
      })
  }

  useEffect(()=>{
    getShow();
  },[])

    return(
      <ScrollView>
        <View style = {styles.container}>
           <ShowDisplay showData={showData} navigation={navigation} />
        </View>
      </ScrollView>
       );
     };
     

但是当我尝试在“显示显示”组件中显示数据时,我只显示了最后一项。这是我的显示显示组件:


export default function ShowDisplay({navigation, showData}) {
  if(showData){
       
console.log(showData);

      return(
        <TouchableOpacity style = {styles.show}onPress={() => navigation.navigate('Shows')}>    
          <View style={styles.text}>
            <Text style={styles.font}>{showData.name}</Text>
          </View>
        </TouchableOpacity>
            );

  }else{

    return(
         <View>
            <Text>Loading data</Text>
          </View>
          )
}

}

如您所见,我创建了一个 console.log 来查看“ShowData”是什么,它是来自 API 的所有循环数据:

Object {
  "desc": "<p>We Brits love our cars but, just like any relationship, sometimes things can get a little rusty. Meet master mechanic Fuzz Townshend and radio and TV presenter Tim Shaw, a petrol-head pair who undertake dramatic automobile interventions across the UK, hoping to return some much-loved motors to their former glory. With a tight deadline to turn each job around without the owners knowing, find out how these neglected classics fell in need of a little loving care – and what Fuzz and Tim can do to get them back on the road.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/100/250748.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/100/250748.jpg",
  },
  "name": "Car S.O.S",
}
Object {
  "desc": "<p>Join car addict Tyler Hoover as he makes his way across America buying the coolest, hardest to find cars at even harder to find prices. As soon as he scores, he puts his new ride to the test, on race tracks, off-road adventures and road trips through the heartland. Tyler then meets up with his mechanic \"The Wizard,\" to diagnose whether he bought a winner or a loser, and decide whether to keep the car or flip it.</p>",
  "image": null,
  "name": "Car Issues",
}
Object {
  "desc": "<p>The drivers of exotic supercars put their street cred on the line against deceptively fast sleeper cars built and modified by true gearheads.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/149/374889.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/149/374889.jpg",
  },
  "name": "Fastest Car",
}
Object {
  "desc": "<p>Funnyman and automotive freak, Adam Carolla, brings you the ultimate car lover's show, featuring awesome cars, epic driving adventures and the best of automotive culture. It's the perfect mix of comedy, shop talk and eye candy brought to you by Adam and his co-hosts, Pulitzer Prize-winning automotive journalist Dan Neil \"TheSmokingTire.com\" founder Matt Farah; and former NBA Champion John Salley.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/57/143804.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/57/143804.jpg",
  },
  "name": "The Car Show",
}
Object {
  "desc": "<p>Two teams, two cars, 72 hours. That's the basic premise for a new action-packed custom-car competition, <b>Car Warriors</b>, that brings the highest levels of automotive expertise together for a non-stop battle of artistry and craftsmanship. <br><br>Each episode of Car Warriors lets viewers witness the fast-forward creation of custom performance cars by two eight-member teams of top-notch professionals – the Car Warriors All Stars vs. a variety of challenger teams – who take their projects from stripped-down shells to high-performance works of art. <br><br>But there's a catch: each team has just 72 hours from the time they first lay eyes on the primered bodies until they roll out their beautiful custom cars that are ready for judging. That's 72 hours of round-the-clock, high-pressure car building.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/15/39919.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/15/39919.jpg",
  },
  "name": "Car Warriors",
}
Object {
  "desc": "<p>Presented by Dermot O'Leary, the Saturday night entertainment show, <b>The Getaway Car</b>, will see couples compete in a series of exciting driving challenges that test the limits of their relationships behind the wheel of a car. Can married couples, grandparents and grandchildren, brothers and sisters or best friends work together to scoop the top prize? Or for that matter, will they still be talking afterwards?</p><p>The Getaway Car is packed with thrills, laughter and challenges. At the centre of the show is the fastest driver of his generation: the enigmatic, the iconic, The Stig. Nobody said winning the money would be easy.</p><p>12 x 60 minute episodes have been ordered.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/37/93224.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/37/93224.jpg",
  },
  "name": "The Getaway Car",
}
Object {
  "desc": "<p>Ichika Tendo is a single mother raising her five year old son alone, while she is assigned to work the doctor car for a general hospital. Unlike an ambulance, the doctor car has a doctor which will use this car to make visits to patients. However Ichika has difficulties with her teamleader Asagi as he wants to get rid of this unit.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/51/128632.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/51/128632.jpg",
  },
  "name": "Doctor Car",
}
Object {
  "desc": "<p><b>Car Hunters</b> follows individuals as they passionately search for their dream car. In each episode we follow a new buyer, aided by a friend or family member, as they check out three unique vehicles and hit the open road for a test drive. We share in the exhilaration and deliberation as they try to decide which ride they will cruise home in. Featured buyers include an empty nester who wants to recapture his youth with a car from his glory days; a father and son duo who are on the hunt for a thrill ride to bond over; a former correctional officer looking to kick off his retirement in style by owning a classic convertible; and a life-long lover of iconic low-riders who's looking to finally buy one of his own!</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/55/138960.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/55/138960.jpg",
  },
  "name": "Car Hunters",
}
Object {
  "desc": "<p>A reality series wherein undercover cops rig a car with cameras and remote control devices and leave it in high crime environments to entice and apprehend car thieves.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/99/248920.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/99/248920.jpg",
  },
  "name": "Bait Car",
}
Object {
  "desc": "<p>In <b>Car Wars</b>, ride along with the UK's only unmarked police force as they take down Greater Manchester's most violent criminals: gangs who use stolen cars for ram raids, burglaries and robberies.</p>",
  "image": Object {
    "medium": "https://static.tvmaze.com/uploads/images/medium_portrait/107/268789.jpg",
    "original": "https://static.tvmaze.com/uploads/images/original_untouched/107/268789.jpg",
  },
  "name": "Car Wars",
}

但是我在屏幕上显示的是:

在此处输入图像描述

如您所见,仅显示了一个节目,并且 console.log 显示有很多节目...如何显示所有节目?我认为这是因为我没有循环通过它,但这不起作用?

所以基本上我已经尝试在这个页面上循环它,而不是在另一个页面上循环它,但不是avial。

我需要做什么才能使所有节目都显示在页面上?

标签: javascriptreact-nativeapiloopsobject

解决方案


您正在遍历获取的数据并将每个数据单独设置为状态。这意味着一旦循环完成,只有最后一个项目被保存,然后显示给用户。相反,将整个项目数组保存到状态,然后为每个项目动态创建一个组件。

fetch('http://api.tvmaze.com/search/shows?q=' + show)
  .then(response => response.json())
  .then(json => {
    const items = json.map(item => ({
      name: json[i].show.name,
      desc: json[i].show.summary,
      image: json[i].show.image
    });
    setShowData(items);
  })
  .catch(error => {
    console.log(error);
  });

然后在渲染函数中:

<View style={styles.container}>
  {showData.map(dataItem => (
    <ShowDisplay showData={dataItem} key={dataItem.name} navigation={navigation} />
  ))}
</View>

注意:通过这种方式showData,现在将是一个数组而不是一个对象。应牢记这一点,并将默认状态值设为空数组。

const [showData, setShowData] = useState([]);

推荐阅读