React Native Deck Swiper

问题描述

我正在尝试使用下面的两个功能组件向端点发出 GET 请求,以显示在我的 React Native 甲板 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);
};

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

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",}....]

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

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

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

  <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 可重用组件访问数组中的任何数据时,例如 card.featured_image

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

//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”的状态来解决该问题。然后,有一个 useEffect 会在 getLatestNews 的长度发生变化时触发。如果 getLatestNews 的长度 > 0,那么您可以将 isDataReturned 设置为 true 并仅在 isDataReturned 为 true 时才渲染甲板。

这是我制作的代码示例:

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

在renderCard属性中,我从

 renderCard={(card) => <Cardz card={card} />}

 renderCard={(card) => (card && <Cardz card={card} />) || null}

它奏效了。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...