简体   繁体   English

循环通过 object 并在 react native 中显示数据

[英]Looping through an object and displaying data in react native

I am attempting to pull data from an api an display it to the user.我正在尝试从 api 中提取数据并将其显示给用户。 I have made a succesful fetch call and I am looping through the data here in my HomeScreen component.我已经进行了成功的 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>
       );
     };
     

But when I attempt to display the data in my 'Show Display' component, I only get the last item displayed.但是当我尝试在“显示显示”组件中显示数据时,我只显示了最后一项。 Here is my Show Display component:这是我的显示显示组件:


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>
          )
}

}

As you can see I have created a console.log to see what 'ShowData' was and it was ALL of looped data from the API:如您所见,我创建了一个 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",
}

But what I get displayed on the screen is this:但是我在屏幕上显示的是:

在此处输入图像描述

As you can see there is only one show displayed and the console.log shows that there are many shows... How do I display all of them?如您所见,仅显示了一个节目,并且 console.log 显示有很多节目...如何显示所有节目? I think it's because i'm not looping through it but that doesn't work?我认为这是因为我没有循环通过它,但这不起作用?

So basically I have tried looping it on this page, not looping it on the other page, but to not avial.所以基本上我已经尝试在这个页面上循环它,而不是在另一个页面上循环它,但不是avial。

What do I need to do to make all the shows show up on the page?我需要做什么才能使所有节目都显示在页面上?

You are looping through the fetched data and setting each one individually to the state.您正在遍历获取的数据并将每个数据单独设置为 state。 This means that once the loop has finished only the last item is saved and then shown to the user.这意味着一旦循环完成,只有最后一个项目被保存,然后显示给用户。 Instead, save the entire array of items to the state and then dynamically create a component for each item.相反,将整个项目数组保存到 state,然后为每个项目动态创建一个组件。

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);
  });

And then in the render function:然后在渲染 function 中:

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

Note: by doing it this way showData will now be an array and not an object.注意:通过这种方式, showData现在将是一个数组,而不是 object。 This should be kept in mind, as well as having the default state value be an empty array.应牢记这一点,并且将默认 state 值设为空数组。

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

Your component would need to look something similar to the below.您的组件需要看起来类似于下面的内容。 The original state for the showData variable is an array ( [] ) and then the data is mapped to a list of ShowDisplay components. showData变量的原始 state 是一个数组 ( [] ),然后将数据映射到ShowDisplay组件列表。 Also, look how each list item has a key attribute (which should be unique), like recommended by React .另外,看看每个列表项如何具有一个key属性(应该是唯一的),就像React推荐的那样。

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([
            ...showData,
            {
              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}>
        {showData.map((data) => (
          <ShowDisplay key={data.name} showData={data} navigation={navigation} />
        ))}
      </View>
    </ScrollView>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM