简体   繁体   中英

React Native : Return conditional Statement in View

I'm facing a weird problem. In my react native app I have conditions that render the View and ScrollView . The problem is the false statement shows first before the true statement, so I have example below let say the PinCodeVisible.showPinLock is true so the Pincode should shown not the false statement which is the text. My problem is it shows first the false statement which is the text and then after it loads the true statement which is pincode , I just want to disregard the text under the false statement since it is false,

why It shown even it is false statement? Did I missed something?

const [PinCodeVisible, setPin] = useState({ PINCodeStatus: "choose", showPinLock: false });

React.useEffect(() => {
setPin({ showPinLock: true});   //let say the pincode is true
 }, [])


return (
    <View style={styles.container} >
        {PinCodeVisible.showPinLock === true ? (

            <PINCode
                // modalVisible={modalVisible}
                status={PinCodeVisible.PINCodeStatus}
                touchIDDisabled={true}
                finishProcess={() => _finishProcess()}
                timeLocked={5000}
            />
        ) :
            <ScrollView style={styles.container}> //this scrollview shown first event the statement is true
                <Text>This text will show before the true statement above</Text>  // it should not shown because the statement is true
            </ScrollView>}
    </View>
)

const styles = StyleSheet.create({
  container: {
    flex: 1,
  }

You can check the following things,

  1. Here if you want to display a true statement on page load then must set true as an initial value of your state only not required to set in useEffect.

const [pinCodeVisible, setPin] = useState({ PINCodeStatus: "choose", showPinLock: true });

  1. If you want to update an object then you can update using the spread operator.

setPin({... pinCodeVisible, showPinLock: true});

  1. In the render method you can use the conditional operator as below
return (
    <View style={styles.container}>
      {(pinCodeVisible.showPinLock && (
        <PINCode
          finishProcess={() => _finishProcess()}
          status={pinCodeVisible.PINCodeStatus}
          timeLocked={5000}
          touchIDDisabled={true}
        />
      )) || (
        <ScrollView style={styles.container}>
          <Text>This text will show before the true statement above</Text>
        </ScrollView>
      )}
    </View>
   );

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