状态未在React Native中更新

时间:2020-05-26 18:27:30

标签: javascript reactjs react-native react-navigation react-navigation-v5

实际上,它并不是在所有地方都可以更新。

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为什么会发生这种情况,但是在代码结尾处的第149行,它可以正常工作,但是在onPress方法的第89行起,它甚至不会更改状态,并且通过没有定义的initialstate本身,我尝试用0和null之类的值对其进行初始化,并且仍然分别console.logged 0和null,因此我进行了undefined的检查,以便如果出现则不会转到下一页。没有真正的价值

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;
再次在下一个屏幕中显示

,即使我未定义它也放开了它,console.logs也未定义,这很明显,我把它放在这里很笨,但这就是它。

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

1 个答案:

答案 0 :(得分:2)

为什么需要在该状态下保存音量?您可以直接在onPress操作中导航:

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

另一种方法是计算音量并将其用于设置状态并用于导航:

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