【问题标题】:Where to make API call in a screen in ReactNative?在 React Native 的屏幕中哪里可以调用 API?
【发布时间】:2019-11-12 19:03:39
【问题描述】:

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

我已阅读 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

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

【问题讨论】:

    标签: react-native mobile


    【解决方案1】:

    你必须使用反应生命周期

    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
    }

    你在datasource中得到api结果。

    【讨论】:

      【解决方案2】:
      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>
              )
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 2021-10-06
        • 2020-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多