簡體   English   中英

重置React Native中組件的狀態?

[英]Reset the state of component in react native?

我想在用戶重新訪問頁面后重置組件的狀態,一旦用戶訪問頁面1並轉到頁面2,然后再次返回頁面1, <TextInput>值仍保留在那里。 我想在用戶更改屏幕后清除, ComponentDidMountComponentWillUnMount不在屏幕更改上運行。

import React from 'react';
import { Image, TextInput, FlatList, StyleSheet, Text, View,TouchableOpacity, ActivityIndicator, Platform } from 'react-native';

export default class RatesScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currency_search: null,

    }
  }
  componentWillUnMount(){
    this.setState({currency_search:null})
  }

  render(){
    return(
      <View>
        <TextInput placeholder="Search" placeholderTextColor="#919191" ref={searchInput => { this.searchInput = searchInput }} onChangeText={currency_search => this.setState({ currency_search: currency_search.toLowerCase() }, this.searchRates)} style={{ padding: 10, borderWidth: 1, borderColor: "#171717", borderRadius: 2, backgroundColor: '#171717', color: "#919191" }} clearButtonMode="always"></TextInput>
      </View>
    )
  }

您可以在page1中使用componentWillUnmount生命周期掛鈎來清除其狀態。

componentWillUnmount(){this.setState({})}。

如果您顯示一些代碼,我可以給您一個更具體的答案。

如果您使用的是react-navigation ,則可以使用導航生命周期回調,

您可以使用屏幕的willBlur清空狀態。

該代碼應如下所示:

//This code should go in componentDidMount.
const didBlurSubscription = this.props.navigation.addListener(
 'willBlur',
  payload => {
    this.setState({}); //whatever the default state you want to set.
  }
);

// Also, Remove the listener when you are done in willUnmount
didBlurSubscription.remove();

您可以在此處了解有關導航生命周期回調和事件的更多信息。

希望這可以幫助。 快樂編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM