如何为反应原生的快照转盘提供API数据

时间:2017-09-25 09:15:52

标签: javascript arrays react-native react-native-fetch-blob react-native-snap-carousel

我正在研究React原生新闻应用程序,我必须从REST API解析数据并将数据提供给snap carousal组件。

snap-carousal有sliderEntry.js,它以键值对数组的形式呈现标题,副标题,插图。

SliderEntry.js

import React, { Component, PropTypes } from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import styles from '../styles/SliderEntry.style';

export default class SliderEntry extends Component {

static propTypes = {
    title: PropTypes.string.isRequired,
    subtitle: PropTypes.string,
    illustration: PropTypes.string,
    even: PropTypes.bool
};

render () {
    const { title, subtitle, illustration, even } = this.props;

    const uppercaseTitle = title ? (
        <Text style={[styles.title, even ? styles.titleEven : {}]}   numberOfLines={2}>{ title.toUpperCase() }</Text>
    ) : false;

    return (
        <TouchableOpacity
          activeOpacity={0.7}
          style={styles.slideInnerContainer}
          onPress={() => { alert(`You've clicked '${title}'`); }}
          >
            <View style={[styles.imageContainer, even ? styles.imageContainerEven : {}]}>
                <Image
                  source={{ uri: illustration }}
                  style={styles.image}
                />
                <View style={[styles.radiusMask, even ? styles.radiusMaskEven : {}]} />
            </View>
            <View style={[styles.textContainer, even ? styles.textContainerEven : {}]}>
                { uppercaseTitle }
                <Text style={[styles.subtitle, even ? styles.subtitleEven : {}]} numberOfLines={2}>{ subtitle }</Text>
            </View>
        </TouchableOpacity>
    );
}
}

我的api以不同的格式返回数据,我必须以sliderEntry.js期望的格式设置状态变量,这是一个数组,所以我创建了新的数组并从api响应中提取了标题,副标题,插图并设置了新数组作为状态变量条目。

import React from "react";
import Carousel from 'react-native-snap-carousel';
import { sliderWidth, itemWidth } from './styles/SliderEntry.style';
import SliderEntry from './components/SliderEntry';
import styles from './styles/index.style';
import { ENTRIES1, ENTRIES2 } from './static/entries';

export default class HomeScreen extends React.Component {

getSlides (entries) {
    if (!entries) {
        return false;
    }

    return entries.map((entry, index) => {
        return (
            <SliderEntry
              key={`carousel-entry-${index}`}
              even={(index + 1) % 2 === 0}
              {...entry}
            />
        );
    });
}

constructor(props) {
super(props);
this.state = {entries: ENTRIES1,entries2:[]};
}

componentDidMount() {
this.load();
}

async load(){
  try { 
    let response = await fetch('http://newstrack.com/api/get_category_posts?id=263');
     let responseJson = await response.json(); 


var responseModified =[
{
    title: 'jhbfb ombop',
    subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur',
    illustration: 'http://i.imgur.com/UYiroysl.jpg'
},
{
    title: 'Earlier this morning, NYC',
    subtitle: 'Lorem ipsum dolor sit amet',
    illustration: 'http://i.imgur.com/UPrs1EWl.jpg'
},
{
    title: 'White Pocket Sunset',
    subtitle: 'Lorem ipsum dolor sit amet et nuncat ',
    illustration: 'http://i.imgur.com/MABUbpDl.jpg'
},
{
    title: 'Acrocorinth, Greece',
    subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur',
    illustration: 'http://i.imgur.com/KZsmUi2l.jpg'
},
{
    title: 'The lone tree, majestic landscape of New Zealand',
    subtitle: 'Lorem ipsum dolor sit amet',
    illustration: 'http://i.imgur.com/2nCt3Sbl.jpg'
},
{
    title: 'Middle Earth, Germany',
    subtitle: 'Lorem ipsum dolor sit amet',
    illustration: 'http://i.imgur.com/lceHsT6l.jpg'
}
];

for (var i = 0; i <8; i++) {
  responseModified [i].title=responseJson.posts[i].title;
  responseModified [i].subtitle=responseJson.posts[i].excerpt;
  responseModified[i].illustration=
        responseJson.posts[i].attachments[0].url;
}


     this.setState({

      entries: responseJson.posts,
      entries2: responseModified

    }, function() {
      // do something with new state


    });
   } catch(error) 
   { 
    console.error(error);
  }
}



render() {
return (
<Carousel
          sliderWidth={sliderWidth}
          itemWidth={itemWidth}
          inactiveSlideScale={1}
          inactiveSlideOpacity={1}
          enableMomentum={true}
          autoplay={true}
          autoplayDelay={500}
          autoplayInterval={2500}
          containerCustomStyle={styles.slider}
          contentContainerCustomStyle={styles.sliderContainer}
          showsHorizontalScrollIndicator={false}
          snapOnAndroid={true}
          removeClippedSubviews={false}
          >
              { this.getSlides(this.state.entries2) }
          </Carousel>
);
}
}

Api结构:

{
 "posts":[
      {
       "title": "We are not looking forward to forming new party",
       "excerpt": "<p>Lucknow: Samajwadi Party patriarch Mulayam",
       "attachments": [
             {
              "url": "http:\/\/abc.com\/wp-content.jpg",
             }
          ]
     },
     {
       "title": "We are not looking forward to forming new party",
       "excerpt": "<p>Lucknow: Samajwadi Party patriarch Mulayam",
       "attachments": [
             {
              "url": "http:\/\/abc.com\/wp-content.jpg",
             }
          ]
     },
     {
       "title": "We are not looking forward to forming new party",
       "excerpt": "<p>Lucknow: Samajwadi Party patriarch Mulayam",
       "attachments": [
             {
              "url": "http:\/\/abc.com\/wp-content.jpg",
             }
          ]
     },
     {...},
     ...  
 ]
}

我正在尝试获取标题,摘录,网址并分配给title.subtitle,插图。这是正确的方法吗?我收到了错误:

  

undefined不是对象(评估'responseModified [i] .title = responseJson.posts [i] .title')

1 个答案:

答案 0 :(得分:1)

要修改数组,您可以先创建空白数组。 喜欢

<强> var arrayModified = [] 之后你可以像这样在数组中插入值

var array = responseJson.posts;
for (let i = 0; i < array.length; i++) {
    if (arrayModified[0] === []) {
        arrayModified.pop();
    } else {
        arrURI.push({
            title: array[i].title,
            subtitle: array[i].imageName,
            illustration: array[i].imageData,
        });
    }
}

据我说这是正确的方法, 并且可能在此之后你不会得到无法解决的错误。