在react native中状态不更新

问题描述 投票:0回答:1

事实上,它并不是到处更新,我想它更新。

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

我不知道为什么会发生这种情况,但是在代码的最后149行,它工作正常,但是在第89行开始的 onPress 我试着用0和null这样的值来初始化它,但它仍然分别是console.logged 0和null,所以我放了一个未定义的检查,这样如果没有真实的值,它就不会进入下一页。

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;

`在下一个屏幕上,如果我让它走,即使它是未定义的,它的控制台.日志未定义,这是很明显的,我把它放在这里是愚蠢的,但就是这样'

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

javascript reactjs react-native react-navigation react-navigation-v5
1个回答
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,
      },
   });
}
© www.soinside.com 2019 - 2024. All rights reserved.