开发者问题收集

React Native 甲板刷卡器

2021-01-07
1845

我正尝试使用下面的两个功能组件向 enpoint 发出 GET 请求,以在我的 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);
};

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

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 不是对象(正在评估“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
2个回答

我以前做过类似的事情,所以我想我可以帮上一点忙。这里的问题是,在卡片呈现之前,您的 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>)
    }
hy_phan
2021-01-09

在 renderCard 属性中,我将其从

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

更改为

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

并且成功了。

Obot Ernest
2021-01-16