简体   繁体   中英

Reset the state of component in react native?

I want to reset the state of the component once the user revisits the page, Once the user visits page 1 and goes to page 2 and again back to page 1 <TextInput> value remains there. I want to clear once the user changes the screen, ComponentDidMount , and ComponentWillUnMount don't run on the screen change.

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

you can use componentWillUnmount lifecycle hook in page1 to clear its state..

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

i can give ua more specific answer if you show some code..

If you are using react-navigation you can use navigation lifecycle callbacks,

you can use willBlur of the screen to empty your state.

The code should look like:

//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();

You can study more about the navigation lifecycle callback and events here .

Hope this helps. Happy Coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM