在屏幕上以反应术中的屏幕呼叫在哪里



我是新手反应本机,我决定实现一个迷你Twitter应用程序。但是我被困在某个地方。如下所示,我有一个名为posty的组件,其中包含一个堆叠的刀片。屏幕是屏幕后和NewPostScreen。当我单击"后屏幕"屏幕标题中的图标时,我可以导航到NewPostscreen来编写新推文。当我编写Tweet并单击NewPostScreen中的按钮时,它会导航回到后屏幕上,但我的新推文不会显示。我想再次打一个API调用以加载我的新推文。

我已经阅读了React Native的文档"导航生命周期"(https://reaectnavigation.org/docs/en/navigation-lifecycle.html(。它说:"考虑带有屏幕A和B的堆栈导航器。导航到A后,将其componentDidMount称为。推动B时,也称其为componentDidMount,但A剩下的A剩余量未调用,因此未调用其componentWillunMount。从b回到a,b的componentWillunMount被称为b,但a的componentDidmount并不是因为剩下的剩余时间一直安装。"

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 LifeCycle

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

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>
        )
    }
}

相关内容

  • 没有找到相关文章

最新更新