导航到屏幕或组件时刷新

时间:2020-02-13 02:03:09

标签: reactjs react-native

我有两个屏幕,一个屏幕用于显示使用API​​的记录,另一个屏幕用于注册。

问题是当我注册并导航到显示屏时,它不会更新。

这是屏幕的结构:

  constructor(props) {
    super(props);
    this.state = {isLoading: true, pendIsLoading: true, dataSource: [], contentStorageS:""}
  };

  fetchDados = async () => {
    let usuario = await AsyncStorage.getItem("ASCOFAR_app_usuario");

    try {
      const response = await api.get("api/listaRegistros.php?usuario="+usuario);
      const responseData = await response.data
      if(responseData.status == "ERRO"){
        this.setState({
          isLoading: false,
          dataSource: "",
        })
      }else{
        this.setState({
          isLoading: false,
          dataSource: responseData,
        })
      }
      console.log(response)

    } catch (error) {
      Alert.alert(error)
    }
  }

async componentDidMount () {
    this.fetchDados();
    this.atualizaState();
  }

    tirarLoad() {
      if(this.state.isLoading == true){
        return (
            <ActivityIndicator size="large" color="#be152c"/>
        )
      }else if(this.state.dataSource == ""){
        return (
          <ScrollView >
            <View style={{justifyContent:"center", alignItems:"center",}}>
              <Image
                style ={{width:150, height:150, marginTop:35}}
                source={require('../assets/images/aguardando.png')}
              />
            </View>

          </ScrollView>
        )
      }else{
        return (
          <ScrollView>
            <Text style={styles.tituloGrid}>Formularios Enviados</Text>
            {this.state.dataSource.map(dados => (
              <View style={styles.list} key={dados.id}>
                <Text style={styles.listChild}>{dados.id}</Text>
                <Text style={styles.listChild}>{dados.nome}</Text>
                <Text>|</Text>
                <Text style={styles.listChild}>{dados.endereco}</Text>
              </View>
            ))}
          </ScrollView>
        )
      }
    }

<View style={styles.grid}>
   {this.tirarLoad()}
</View>

导航到此屏幕以更新API使用情况时,我需要知道该怎么做

3 个答案:

答案 0 :(得分:0)

假设您使用的是React-Navigation,您是否尝试添加监听器

focus react-navigation documentation

您也可以通过componentDidUpdate进行操作。我找不到在5.x上执行此操作的官方文档。我相信它仍适用于5.x。 (Doc on 3.x


import { withNavigationFocus } from "react-navigation";

componentDidUpdate(prevProps) {
    if (prevProps.isFocused !== this.props.isFocused) {
      this.fetchDados()
      //or other similar onFocus function
    }
  }

export default withNavigationFocus(TabScreen);

答案 1 :(得分:0)

尝试在导航后重新呈现主屏幕

this.props.navigation.navigate('Home', {
      onBack: () => this.refresh() //function to refresh screen,
    });

答案 2 :(得分:0)

ImageView