簡體   English   中英

React Native Deck Swiper

[英]React Native Deck Swiper

我正在嘗試使用下面的兩個功能組件向 enpoint 發出 GET 請求,以顯示在我的 react native 甲板掃描器中

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

我現在將數據保存到 state 數組中

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.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 state 在卡片渲染之前尚未更新。 您可以通過另一個名為“isDataReturned”的 state 來解決此問題。 然后,有一個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}

它奏效了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM