在ReactNative的屏幕上哪里可以进行API调用?

时间:2019-07-02 07:20:23

标签: react-native mobile

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

我已经阅读了React Native(https://reactnavigation.org/docs/en/navigation-lifecycle.html)的文档“ Navigation lifecycle”。它说:“考虑具有屏幕A和B的堆栈导航器。导航到A后,将调用其componentDidMount。按下B时,还将调用其componentDidMount,但是A仍安装在堆栈上,因此不调用其componentWillUnmount。从B返回到A,将调用B的componentWillUnmount,但是A的componentDidMount并不是因为A始终保持挂载状态。”

Posty.js

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

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

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调用?

2 个答案:

答案 0 :(得分:0)

您必须使用反应生命周期

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结果。

答案 1 :(得分:0)

ItemTemplate