Как сбросить состояние в компоненте дочернего класса одновременно с родительским компонентом в React Native?

Я новичок в React Native и пытаюсь очистить состояние дочернего компонента одновременно с родительским.

Я пытаюсь сделать следующее:

  1. После перехода от MainMap.js к последнему экрану TripsListScreen.js (весь процесс представляет собой стек из 4 экранов, вложенных в ящик), я получил все данные, хранящиеся в магазине Redux, и отобразил их в TripsListScreen.
  2. Затем я нажимаю кнопку add, чтобы создать новые поездки. Я успешно сбросил состояние на MainMap. Однако состояния (value prop of TextInput) в компоненте PlaceInput все еще там. Как мы можем это сбросить?

Вот состояния MainMap.js:

const initialState = {
    hasMapPermission: false,
    _userLocationDisplayed: null,
    userLatitude: 0,
    userLongitude: 0,
    initial_UserLatitude: 0,
    initial_UserLongitude: 0,
    userLocationAddress: '',

    destination: [],
    destinationName: [],
    destinationAddress: [],
    destinationCoords: [],
    destinationImageUri: [],

    numOfInput:[0,1],
    counter: 1,
    wayPoints: [],
    markers: [],

    doCleanState: 'no' // Right here I want to pass the prop from PlaceInput as this.state.doCleanState
};
const cleanUpState = {
    hasMapPermission: false,

    destination: [],
    destinationName: [],
    destinationAddress: [],
    destinationCoords: [],
    destinationImageUri: [],

    numOfInput:[0,1],
    counter: 1,
    wayPoints: [],
    markers: [],

    doCleanState: 'yes'
}

class MainMap extends React.Component{

    constructor(props){
        super(props);
        this.state = initialState;
    };


    componentDidMount(){
        console.log('Hello',this.props);
        console.log('This is state', this.state);
        this._requestUserLocation();
        this._unsubscribe = this.props.navigation.addListener('focus', () => {
            this.setState(cleanUpState);

        })
    };

    componentWillUnmount(){
        Geolocation.clearWatch(this.watch_location_id);
        this._unsubscribe();

    }

   render(){
      return(
        //...
        <PlaceInput
            id={itemData}

            defaultValue={this.state._userLocationDisplayed}
            displayDefaultValue={!index}
            doCleanState={this.state.doCleanState}
       />
  );
}

По сути, я пытался передать опору из PlaceInput как состояние в MainMap. При сбросе состояний MainMap (состояние doCleanState также изменяется, а не сбрасывается), состояния PlaceInput не сбрасываются

Вот PlaceInput:

//...
class PlaceInput extends React.Component{

    constructor(props){
        super(props);
        this.state={
            predictions: [],
            destinationInput: '',
        }
    }

    componentDidUpdate(prevProps){
        if(this.props.doCleanState !== prevProps.doCleanState){
            this.setState({
                destinationInput: '',
            })
        }
    }

    render(){
        return(
            <TextInput 
                key={this.id}

                placeholder='Search your places'

                onChangeText={(input) => {
                    this.setState({destinationInput: input});
                    this.getPlacesDebounced(input);
                }}
                value={this.props.displayDefaultValue ? this.props.defaultValue : this.state.destinationInput} // props.defaultValue is state of MainMap : 'Your location'
                             // destinationInput is what the users type

             />
   );
}
//...

Когда я возвращаюсь к MainMap, состояние destinationInput все еще присутствует в PlaceInput

Проблема

ПОМОГИТЕ !!!


person Ken Pham    schedule 28.03.2020    source источник


Ответы (2)


В компоненте PlaceInput передайте значение props родительскому элементу, где хотите,

class PlaceInput extends React.Component{

    //... your code method
    this.props.updateClean("") // pass your value to parent

}

Затем в компоненте MainMap

<PlaceInput
        id={itemData}

        defaultValue={this.state._userLocationDisplayed}
        displayDefaultValue={!index}
        doCleanState={this.state.doCleanState}
        updateClean={(text)=> setState({doCleanState:text})} // <-- change like this. 
   />
person Ravi Kumar Karunanithi    schedule 28.03.2020

Посмотрите, поможет ли это:

class MainMap extends React.Component{
  // ...
    componentDidMount(){
        // ...
        this._unsubscribe = this.props.navigation.addListener('focus', () => {
          // destructure the cleanUpState so you aren't passing a global reference around
          this.setState({...cleanUpState});
        });
    };
    // ...

Когда вы просто назначаете состояние cleanUpState, теперь у вас есть ссылка на этот глобальный объект, и вы изменяете его во всем приложении. Убедитесь, что вы деструктурируете объекты, чтобы передавать их копии, а не ссылки.

person DanielSchroederDev    schedule 28.03.2020