简体   繁体   English

state 在本机反应中未更新

[英]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知道为什么会发生这种情况,但是在第 149 行,接近代码的末尾,它工作正常,但在onPress方法的第 89 行开始,它不会改变 state 即使在那里,它传递了未定义的初始状态本身,我尝试使用 0 和 null 之类的值对其进行初始化,但它仍然分别在 console.logged 0 和 null 中,所以我检查了 undefined 以便它不会 Z34D1F91FB2E514B8576FAB1A75A9 到真正的值

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' `再次在下一个屏幕中,如果我让它 go 即使它是未定义的,它 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

Why do you need to save the volume in the state?为什么需要在 state 中保存音量? You can navigate directly in the onPress action:您可以直接在 onPress 操作中导航:

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:另一种方法是计算音量并使用它来设置 state 和导航:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM