Estoy tratando de pasar el estado entre pantallas. Seguí las instrucciones de Pasando parámetros a rutas Puedo pass state desde mi pantalla de inicio a pantalla de detalles, pero cuando trato de pass back state de la pantalla de detalles a la pantalla de inicio, el estado no es satisfactorio.

Tengo el botón de acuerdo en la pantalla de inicio y cuando check on the button y navego a la pantalla de detalles, button is checked (hasta ahora bien).

Sin embargo, si uncheck el botón de la pantalla de detalles and navigate back to Home screen the state is still marcó`.

Prueba el código de la expo

Este es mi código de pantalla de inicio:

const imageOn = require("./iconCheck.png");
const imageOff = require("./emptyCheck.png");

class HomeScreen extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      agreeState: this.props.navigation.getParam('agreeServiceFromChild'),
    };
  }

  checkStateImage(){
    if(this.state.agreeState === undefined){this.setState({agreeState:false},()=>console.log(this.state.agreeState,'agreeState'))}
    if(this.state.agreeState === true){return(imageOn)}
    if(this.state.agreeState === false){return(imageOff)}
  }
  render() {
        const { navigation } = this.props;

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <CustomCheckBox
          onPress={() => this.setState({agreeState: !this.state.agreeState}, ()=> console.log (this.state.agreeState,'agreeState'))}
          onPressButton={() =>
            this.props.navigation.navigate('Details', {
              agreeServiceFromParent:this.state.agreeState,
            })
          }
          source={this.checkStateImage()}
          text='agree'
          buttonText='go to DetailScreen'

        />
      </View>
    );
  }
}

Este es mi código de pantalla de detalles:

class DetailsScreen extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      agreeState:this.props.navigation.getParam('agreeServiceFromParent'),
    };
  }

    checkStateImage(){
    if(this.state.agreeState === undefined){return(imageOff)}
    if(this.state.agreeState != undefined && this.state.agreeState === true){return(imageOn)}
    if(this.state.agreeState != undefined && this.state.agreeState === false){return(imageOff)}
  }

  render() {
    const { navigation } = this.props;
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
         <CustomCheckBox
        onPress={() => this.setState({ agreeState: !this.state.agreeState}, ()=> console.log(this.state.agreeState,'agreeServiceFromChild childview'))}
        source={this.checkStateImage()}
        text="agree"
        onPressButton={() =>
            this.props.navigation.navigate('Home', {
              agreeServiceFromChild:this.state.agreeState,
            })
          }
        buttonText='go to HomeScreen'
      />
      </View>
    );
  }
}
0
kirimi 3 oct. 2019 a las 10:39

1 respuesta

La mejor respuesta

En lugar de poner el constructor, intente ponerlo en componentDidMount (). PFB el código ive actualizado de expo snaack. y he usado navigation.push en lugar de navigation.navigate, coz push siempre hace un push implícito en la parte superior de la pila del navegador.,

import React from 'react';
import { Button, View, Text, TouchableOpacity, Image } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

const imageOn = require("./iconCheck.png");
const imageOff = require("./emptyCheck.png");

class HomeScreen extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      agreeState: false,
    };
  }

  componentDidMount(){
    let stateOfBut = this.props.navigation.getParam('agreeServiceFromChild');
    this.setState({agreeState:stateOfBut})
  }

  checkStateImage(){
    if(this.state.agreeState === undefined){this.setState({agreeState:false},()=>console.log(this.state.agreeState,'agreeState'))}
    if(this.state.agreeState === true){return(imageOn)}
    if(this.state.agreeState === false){return(imageOff)}
  }
  render() {
        const { navigation } = this.props;

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <CustomCheckBox
          onPress={() => this.setState({agreeState: !this.state.agreeState}, ()=> console.log (this.state.agreeState,'agreeState'))}
          onPressButton={() =>
            this.props.navigation.navigate('Details', {
              agreeServiceFromParent:this.state.agreeState,
            })
          }
          source={this.checkStateImage()}
          text='agree'
          buttonText='go to DetailScreen'

        />
      </View>
    );
  }
}

class DetailsScreen extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      agreeState:this.props.navigation.getParam('agreeServiceFromParent'),
    };
  }

    checkStateImage(){
    if(this.state.agreeState === undefined){return(imageOff)}
    if(this.state.agreeState != undefined && this.state.agreeState === true){return(imageOn)}
    if(this.state.agreeState != undefined && this.state.agreeState === false){return(imageOff)}
  }

  render() {
    const { navigation } = this.props;
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
         <CustomCheckBox
        onPress={() => this.setState({ agreeState: !this.state.agreeState}, ()=> console.log(this.state.agreeState,'agreeServiceFromChild childview'))}
        source={this.checkStateImage()}
        text="agree"
        onPressButton={() =>
            this.props.navigation.push('Home', {
              agreeServiceFromChild:this.state.agreeState,
            })
          }
        buttonText='go to HomeScreen'
      />
      </View>
    );
  }
}

const CustomCheckBox = ({ onPress, source, text, onPressButton, buttonText }) => (
    <View
      style={{
        marginTop: 14,
        height: 100,
        width: 310,
        backgroundColor: "transparent",
        alignItems: "center",
        justifyContent: "flex-start",
      }}
    >
    <TouchableOpacity onPress={onPress}>
      <View
        style={{
          marginLeft: 7,
          flexDirection:'row',
          backgroundColor: "white",
          borderRadius: 10,
          alignItems: "center",
          justifyContent: "center"
        }}
      >
      <Image style={{ width: 21, height: 21 }} source={source} />
          <Text style={{ marginLeft: 8 }}>{text}</Text>

      </View>

      </TouchableOpacity>

      <Button title={buttonText} onPress={onPressButton}/>

    </View>
);

const RootStack = createStackNavigator({
  Home: HomeScreen,
  Details: DetailsScreen,
});

export default createAppContainer(RootStack);
1
Gaurav Roy 3 oct. 2019 a las 14:09