簡體   English   中英

state 在本機反應中未更新

[英]state is not updating in react native

實際上它並沒有在任何地方更新,我想它會更新。

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 行,接近代碼的末尾,它工作正常,但在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;

`再次在下一個屏幕中,如果我讓它 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

為什么需要在 state 中保存音量? 您可以直接在 onPress 操作中導航:

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

另一種方法是計算音量並使用它來設置 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