React Native Deck Swiper [英] React Native Deck Swiper

查看:25
本文介绍了React Native Deck Swiper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的两个功能组件向一个 enpoint 发出 GET 请求,以显示在我的 react native deck swipper 中

I am trying to make a GET request to an enpoint using the two functional components below to display in my react native deck swipper

 //using fetch
const getDataUsingFetch = () => {
 fetch(latestNews+ApiKey)
   .then((response) => response.json())
   .then((responseJson) => {
     // set the state of the output here
       console.log(responseJson);
    setLatestNews(responseJson);
   })
   .catch((error) => {
     console.error(error);
   });
}

  //using anxios
  //asynchronous get request call to fetech latest news
const getDataUsingAnxios = async () => {

    //show loading
    setLoading(true);
    setTimeout(async () => {
      //hide loading after the data has been fetched
    setLoading(false);
    try {
      const response = await axios.get(latestNews+ApiKey);
      setLatestNews(response.data);
                setLoading(false);
        console.log(getLatestNews);
    } catch (error) {
      // handle error
      alert(error.message);
      }
    }, 5000);
};

从控制台记录时返回的数据:

Data returned when logged from console:

Array [
  Object {
    "category_id": "8",
    "content": "Hi",
    "created_at": "2020-11-12T12:43:03.000000Z",
    "featured_image": "splash-background_1605184983.jpg",
    "id": 19,
    "news_url": "doerlife.com",
    "title": "I m good how about you",
    "updated_at": "2020-11-12T12:43:03.000000Z",
  }....]

我现在将数据保存到状态数组中

I now save the data into a state array

const [getLatestNews, setLatestNews] = useState([]);

这是我的 swipper(省略了一些代码 - 没有必要)

Here is my swipper(some code ommited - not necessary)

  <Swiper
    ref={useSwiper}
    //cards={categoryID(docs, "2")}
    cards={getLatestNews}
    cardIndex={0}
    backgroundColor="transparent"
    stackSize={2}
    showSecondCard
    cardHorizontalMargin={0}
    animateCardOpacity
    disableBottomSwipe
    renderCard={(card) => <Card card={card} />}
    .....

当我尝试从我的卡片可重用组件访问数组中的任何数据时,例如 card.featured_image

When I try to access any data in the array from my Card reusable component, e.g card.featured_image

我会得到这个错误 - TypeError: undefined is not an object (evalating 'card.featured_image').请有人帮助我.

I WILL GET THIS ERROR - TypeError: undefined is not an object (evaluating 'card.featured_image'). PLEASE CAN SOMEONE HELP ME.

//Card reusable component for deck swipper
import React from 'react'
import { View, Text, Image, ImageSourcePropType } from 'react-native'
import styles from './Card.styles'
const Card = ({ card }) => (
  <View activeOpacity={1} style={styles.card}>
    <Image
      style={styles.image}
      source={card.featured_image}
      resizeMode="cover"
    />

    <View style={styles.photoDescriptionContainer}>
      <Text style={styles.title}>{`${card.title}`}</Text>
      <Text style={styles.content}>{`${card.content}`}</Text>
      <Text style={styles.details}>
        Swipe Left to read news in details
      </Text>
    </View>
  </View>
);
export default Card

推荐答案

我以前做过类似的事情,所以我想我可以提供一些帮助.这里的问题是您的 getLatestNews 状态在卡片呈现之前尚未更新.您可以通过设置另一个名为isDataReturned"的状态来解决此问题.然后,有一个 useEffectgetLatestNews 的长度改变时触发.如果 getLatestNews 的长度是 >0,那么你可以设置 isDataReturned 为真,并且只在 isDataReturned 为真时渲染卡片组.

I've done something similar to this before so I think I can help a bit. The problem here is that your getLatestNews state has not been updated yet before the cards render. You can fix the problem by having another state called "isDataReturned". Then, have a useEffect that triggers whenever getLatestNews's length changes. If getLatestNews's length is > 0, then you can set isDataReturned to be true and render the deck only when isDataReturned is true.

这是我制作的代码示例:

Here's a code sample that I made:

const [getLatestNews, setLatestNews] = useState([]);
const [dataIsReturned, setDataIsReturned] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        'https://cat-fact.herokuapp.com/facts',
      );
      setLatestNews(result.data);
    };

    fetchData();
  }, []);

  useEffect(() => {
    if (getLatestNews.length > 0) {
      setDataIsReturned(true)
    } else {
      setDataIsReturned(false)
    }
  }, [getLatestNews.length])

    if( dataIsReturned === true) {
      return (
      <View style={styles.container}>
         <Swiper
            cards={getLatestNews}
            renderCard={(card) => {
                return (
                  <View style={styles.card}>
                    <Text>{card.text}</Text>
                  </View>
                    
                )
            }}
            onSwiped={(cardIndex) => {console.log(cardIndex)}}
            onSwipedAll={() => {console.log('onSwipedAll')}}
            cardIndex={0}
            backgroundColor={'#4FD0E9'}
            stackSize= {3}>
        </Swiper>
    </View>)
    } else {
     return(<Text>Loading</Text>)
    }

这篇关于React Native Deck Swiper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆