首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ReactNative的屏幕中,在哪里进行API调用?

在ReactNative的屏幕中,在哪里进行API调用?
EN

Stack Overflow用户
提问于 2019-07-02 15:20:24
回答 2查看 1.4K关注 0票数 0

我是React Native的新手,我决定实现一个迷你Twitter应用程序。但我被困在某个地方了。如下所示,我有一个名为Posty的组件,其中包含一个StackNavigator。屏幕是PostScreen和NewPostScreen。当我单击PostScreen屏幕标题中的图标时,我可以导航到NewPostScreen来编写新的tweet。当我编写推文并单击NewPostScreen中的按钮时,它会导航回PostScreen,但我的新推文不会显示。我想再次调用API来加载我的新tweet。

我已经阅读了React Native (https://reactnavigation.org/docs/en/navigation-lifecycle.html)的文档“导航生命周期”。它说:“考虑一个具有屏幕A和B的堆栈导航器。在导航到A之后,它的componentDidMount被调用。当推送B时,它的componentDidMount也被调用,但A仍然挂载在堆栈上,因此它的componentWillUnmount不被调用。当从B返回到A时,B的componentWillUnmount被调用,但A的componentDidMount没有被调用,因为A始终保持挂载。”

Posty.js

代码语言:javascript
复制
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import PostScreen from './screens/PostScreen';
import NewPostScreen from './screens/NewPostScreen'

// Posty adında komponentimi oluşturdum.
// Bu komponent çağrıldığında bir stack navigator exportlamak istediğim için ana komponent Musical'ımın 
// içine PostStack stack navigator komponentimi yerleştirdim.
// Stack navigtor ımın içine screenler tanımladım.

export default class Posty extends React.Component{
  render(){
    return(
      <PostStack />
    );
  }
}


// Yeni bir stack navigator oluşturdum ve adını PostNavigator koydum.
const PostNavigator = createStackNavigator({
  Post: {screen: PostScreen},
  NewPost: {screen: NewPostScreen}
});

// PostStack adlı containerımı yarattım ki Posty Component'inin içinde kullanabileyim.
const PostStack = createAppContainer(PostNavigator);

PostScreen.js

代码语言:javascript
复制
import React, { Component } from 'react';
import PostList from '../PostList'
import {TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome'
import { connect } from 'react-redux';

class PostScreen extends Component {
  constructor(props){
    super(props)

  }

  static navigationOptions = ({ navigation: { navigate } }) =>({
    headerTitle: 'Posts',

    headerRight:<TouchableOpacity onPress={() => navigate('NewPost')}>
                  <Icon style={{marginRight:15}} size={25} name='pencil' />
                </TouchableOpacity>
  })

  render() {
    return (
        <PostList></PostList>
    );
  }
}

const mapStateToProps = state => {
  return{
    id: state.id
  }
}

export default connect(mapStateToProps)(PostScreen);

NewPostScreen.js

代码语言:javascript
复制
import React, {Component} from 'react';
import {TextInput,View,Image,TouchableHighlight,StyleSheet,Text} from 'react-native';
import axios from 'axios';
import {connect} from 'react-redux';

class NewPostScreen extends Component {
    constructor(props) {
      super(props);
      this.state = { text: 'What are you thinking?' };
    }

    onButtonClicked(){
      console.log(this.state.text)
      const {navigate} = this.props.navigation
      axios.post("http://172.29.193.96:5000/newPost",
      {
        author_id: this.props.id,
        content: this.state.text
      }).then(
        navigate('Post')
      )
    }

    render() {
      console.log("NewPostScreen id: ", this.props.id)
      return (
          <View>
              <View style={{flexDirection:'row'}}>
                <Image source={require('../../images/cat.png')}></Image>
                <TextInput
                    style={{height: 100, width:350, textAlign:'auto', fontSize:20, marginTop:30, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={(text) => this.setState({text})}
                    placeholder={this.state.text}
                />
              </View>
              <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={this.onButtonClicked.bind(this)}>
                  <Text style={styles.loginText}>Ekle</Text>
              </TouchableHighlight>
          </View>


      );
    }
  }

  const styles = StyleSheet.create({
    buttonContainer: {
      height:45,
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      marginTop:20,
      marginBottom:30,
      marginLeft: 240,
      width:150,
      borderRadius:30,
    },
    textContainer: {
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      marginBottom: 15,
      width:150,
      borderRadius:30
    },
    loginButton: {
      backgroundColor: "#00b5ec",
    },
    loginText: {
      color: 'white',
      fontSize: 16
    }
  })

const mapStateToProps = state => {
  return{
    id: state.id
  }
} 

export default connect(mapStateToProps)(NewPostScreen);

那么,我应该把我的API调用放在屏幕的哪个方法中再次调用呢?

EN

回答 2

Stack Overflow用户

发布于 2019-07-02 15:33:27

您必须使用react生命周期

代码语言:javascript
复制
componentDidMount(){
fetch("https://YOUR_API")
.then(response => response.json())
.then((responseJson)=> {
  this.setState({
   loading: false,
   dataSource: responseJson
  })
})
.catch(error=>console.log(error)) //to catch the errors if any
}

您可以在数据源中获取api结果。

票数 0
EN

Stack Overflow用户

发布于 2019-07-02 15:47:24

代码语言:javascript
复制
export default class APICALLDEMO extends Component{

 callAPI  = () => {
            return fetch('API URL')
                .then((response) => response.json())
                .then((responseJson) => {
                    this.setState({
                        isLoading: false,
                        dataSource: responseJson.movies,
                    }, function() {
                    });
                }).catch((error) => {
                    console.error(error);
                });
        }


      render(){

            return(
     <View>
      <TouchableOpacity onPress={()=>this.callAPI()}>
                <Text>Call API</Text>
                </TouchableOpacity>
     </View>
        )
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56847257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档