首页 > 解决方案 > 按下按钮后呈现获取结果

问题描述

我有一个从服务器(json)获取的文章列表。将有两个服务器调用。我的意思是现在我在一个 . 下面列出了一些文章标题(从 server1 获取)。Card下面会有一个添加按钮用于复制和粘贴新文章链接(将保存到不同的服务器)。所以我正在尝试将这些新添加的文章附加到我现有的列表中(就像在袖珍应用程序中一样)。我该怎么做?我'已经尝试过类似下面的方法。但是我遇到了错误,可能是一个小错误,请帮我弄清楚。因为渲染应该只在button点击后发生(用于查看新添加的)。所以state也会在那个权利之后设置?我怎样才能做到这一点?

 import {article} from './data';  //json
    import AddNewarticle from './AddNewarticle';
    class SecondScreen extends Component {
         state= {
         newarticle: []
         };
// request for saving newly added article 
onPressSubmit(){    
  fetch('www.mywebsite.com',{
    method: 'POST',
    headers:{
          'Accept': 'application/json',
          'Content-Type': 'application/json',
    },
            body: JSON.stringify({
                url: this.state.url,
            })
})  
  .then(response => response.json())
 .then((responseData) => this.setState({newarticle: responseData}));
    }
renderArticle(){
        this.state.newarticle.message.map(newlist =>
        <AddNewarticle key ={newlist.title} newlist={newlist} />
        );
    }
render(){
return(
<ScrollView>
{article.map(a =>
<CardSection>
<Text>
      {a.title}</Text>
</CardSection>
{this.renderArticle()}
</ScrollView>
<Icon
              raised
              name="check"
              type="feather"
              color="#c1aba8"
              iconStyle={{ resizeMode: "contain" }}
              onPress={() => {
                this.onPressSubmit();
              }}
            />
);
}

我的newarticle(json)也如下。提交新文章后我从服务器得到的响应。

{
    "message": {
        "authors": [
            "Zander Nethercutt"
        ],
        "html": "<div><p name=\"c8e3\" id=\"c8e3\" class=\"graf graf--p graf--hasDropCapModel graf--hasDropCap graf--leading\">The presence of advertising in  This is the power of branding.",
        "title": "The Death of Advertising – Member Feature Stories – Medium"
    },
    "type": "success"
}

我得到的错误newarticle是未定义的。

标签: javascriptreact-nativerenderingfetch

解决方案


import React, { Component } from 'react';
import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert,Image, Platform } from 'react-native';

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true
        }
    }

    GetItem (flower_name) {
        Alert.alert(flower_name);
    }

    componentDidMount() {
        return fetch('https://reactnativecode.000webhostapp.com/FlowersList.php')
            .then((response) => response.json())
            .then((responseJson) => {
                let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
                this.setState({
                    isLoading: false,
                    dataSource: ds.cloneWithRows(responseJson),
                }, function() {
                    // In this block you can do something with new state.
                });
            })
            .catch((error) => {
                console.error(error);
            });
    }

    ListViewItemSeparator = () => {
        return (
            <View
                style={{
                    height: .5,
                    width: "100%",
                    backgroundColor: "#000",
                }}
            />
        );
    }

    render() {
        if (this.state.isLoading) {
            return (
                <View style={{flex: 1, paddingTop: 20}}>
                    <ActivityIndicator />
                </View>
            );
        }

        return (
            <View style={styles.MainContainer}>
                <ListView
                    dataSource={this.state.dataSource}
                    renderSeparator= {this.ListViewItemSeparator}
                    renderRow={(rowData) =>
                        <View style={{flex:1, flexDirection: 'row'}}>
                            <Image source = {{ uri: rowData.flower_image_url }} style={styles.imageViewContainer} />
                            <Text onPress={this.GetItem.bind(this, rowData.flower_name)} style={styles.textViewContainer} >{rowData.flower_name}</Text>
                        </View>
                    }
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    MainContainer :{
        // Setting up View inside content in Vertically center.
        justifyContent: 'center',
        flex:1,
        margin: 5,
        paddingTop: (Platform.OS === 'ios') ? 20 : 0,
    },
    imageViewContainer: {
        width: '50%',
        height: 100 ,
        margin: 10,
        borderRadius : 10
    },
    textViewContainer: {
        textAlignVertical:'center',
        width:'50%',
        padding:20
    },
    tabIcon: {
        width: 16,
        height: 16,
    }
});

AppRegistry.registerComponent('App', () => App);

export default App;

推荐阅读