简体   繁体   中英

state is not updating in react native

Actually it is not updating everywhere i suppose it to update.

import React, { useState, useRef } from "react";
import {
  View,
  Text,
  StyleSheet,
  StatusBar,
  ScrollView,
  TouchableOpacity,
  Dimensions,
  ActivityIndicator,
} from "react-native";

import { TextField } from "react-native-material-textfield";

import Colors from "../constants/Colors";

const welcomescreen = (props) => {
  let [length, setLength] = useState();
  let [breadth, setBreadth] = useState();
  let [height, setHeight] = useState();
  let [volume, setVolume] = useState();

  const [loading, setLoading] = useState(false);

  const lengthInputHandler = (l) => {
    setLength(l);
  };
  const breadthInputHandler = (br) => {
    setBreadth(br);
  };
  const HeightInputHandler = (h) => {
    setHeight(h);
  };

  let lengthIntPart,
    breadthIntPart,
    heightIntPart,
    lengthinInches,
    breadthinInches,
    heightinInches,
    res;

  const volumeCalc = () => {
    lengthIntPart = Math.floor(parseFloat(length));
    lengthinInches =
      (lengthIntPart + (parseFloat(length) - lengthIntPart) / 1.2) * 12;

    breadthIntPart = Math.floor(parseFloat(breadth));
    breadthinInches =
      (breadthIntPart + (parseFloat(breadth) - breadthIntPart) / 1.2) * 12;

    heightIntPart = Math.floor(parseFloat(height));
    heightinInches =
      (heightIntPart + (parseFloat(height) - heightIntPart) / 1.2) * 12;

    res = lengthinInches * breadthinInches * heightinInches;

    return res;
  };

  return (
    <ScrollView style={styles.screen}>
      <StatusBar barStyle="dark-content" />

      <View style={styles.form}>
        <TextField
          label="Length"
          onChangeText={lengthInputHandler}
          keyboardType="numeric"
          textAlignVertical="center"
        />
        <TextField
          label="Breadth"
          onChangeText={breadthInputHandler}
          keyboardType="numeric"
        />
        <TextField
          label="Height"
          onChangeText={HeightInputHandler}
          keyboardType="numeric"
        />
      </View>

      <View style={{ alignItems: "center" }}>
        <TouchableOpacity
          style={styles.calcBtn}
          onPress={() => {
            setVolume(volumeCalc());
            setLoading(true);
            setTimeout(() => {
              if (volume !== undefined) {
                props.navigation.navigate({
                  name: "resultscreen",
                  params: {
                    volume: volume,
                  },
                });
              }
              setLoading(false);
              console.log(volume);
            }, 3000);
          }}
          disabled={!!!length && !!!breadth && !!!height}
        >
          {!loading ? (
            <Text style={styles.text}>Calculate</Text>
          ) : (
            <ActivityIndicator size="small" color={Colors.white} />
          )}
        </TouchableOpacity>
      </View>
      <View style={{ width: "90%" }}>
        <View style={{ flexDirection: "row", justifyContent: "space-around" }}>
          <Text>Volume :</Text> 
          <Text>{volume} cubic inches </Text> //line 14
        </View>
        <View style={{ flexDirection: "row", justifyContent: "space-around" }}>
          <Text>Volume:</Text>
          <Text>{volume / 1728} Cb. Feet</Text>
        </View>
        <View style={{ flexDirection: "row", justifyContent: "space-around" }}>
          <Text>Weight:</Text>
          <Text>{volume / 1728 / 25} Metric tonne</Text>
        </View>
      </View>
    </ScrollView>
  );
};


export default welcomescreen;

lines numbers are mentioned in comments of the code

idk why that is happening but at line 149, towards the end of the code, it works fine but at line 89 onwards in the onPress method,it does not change the state even there, and it passes the initialstate itself which is not defined, i tried initializing it with values like 0 and null and it still console.logged 0 and null respectively, so i put in a check for undefined so that so that it does not go to the next page if there is no real value

the next screen aka resultscreen

import React from "react";
import { View, Text } from "react-native";

const ResultScreen = (props) => {
  const volume = props.route.params.volume;
  console.log(volume);
  return (
    <View>
      <Text>{volume}</Text>
    </View>
  );
};

export default ResultScreen;

`again in the next screen if i let it go even if it is undefined, it console.logs undefined, which is quite obvious and dumb of me to put it here, but that is it'

i have no idea why this is happening

NOTE: But if i press the button twice, it updates the state on the second click, its strange that is happening

Why do you need to save the volume in the state? You can navigate directly in the onPress action:

onPress={() => {
   let calculatedVolume = volumeCalc();
   props.navigation.navigate({
      name: "resultscreen",
      params: {
         volume: calculatedVolume,
      },
   });
}

Another approch is to calculate the volume and use it to set the state and for your navigation:

onPress={() => {
   let calculatedVolume = volumeCalc();
   setVolume(calculatedVolume);
   props.navigation.navigate({
      name: "resultscreen",
      params: {
         volume: calculatedVolume,
      },
   });
}

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