为什么我的react原生组件一直在刷新



hi我正在尝试构建react原生应用程序,我正在使用expo我构建了一个屏幕来显示数据,并使用钩子计算一个数字但我面对的是,我的组件一直在渲染,所以我无法轻松按下按钮,这导致我无法计算数字,这是我的代码,我可以如何停止这种持续刷新

如果我在组件中包含控制台语句,它将继续在控制台中打印,而不会停止

import React, { useState, useEffect } from "react";
import { AsyncStorage } from "react-native";
import { Button } from "react-native-paper";
import axios from "axios";
import { View, Text, TextInput, StyleSheet } from "react-native";
export default function Confirm() {
const [info, setInfo] = useState([]);
const [value, onChangeText] = React.useState("0");
const [total, setTotal] = useState("0");
const [selectedLocation, setSelectedLocation] = useState({});
try {
//Retrieving user token, reserved nanny information and user location value from AsyncStorage
AsyncStorage.multiGet(["token", "nany", "location"]).then((res) => {
var nany = JSON.parse(res[1][1]);
var location = JSON.parse(res[2][1]);
setInfo(nany);
console.log("hi3");
setSelectedLocation(location);
});
} catch (error) {
throw error;
}

const onSubmit = () => {
axios
.post("http://192.168.127.43:5000/send2", [selectedLocation, total, info])
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
function calculateTotal() {
console.log(info.cost * value);
var totalCost = info.cost * value;
setTotal(totalCost);
alert("Your reservation done n Your service costs: " + total);
}
return (
<View>
<>
<View>
<Card
title={info.name}
caption={info.cost + "  JD  /H"}

>
<View

>
<Text>{info.place}</Text>
</View>
</Card>
<View>
<View>
<Text style={styles.text}>
Enter how many hours you need our service
</Text>
<TextInput
style={styles.input}
onChangeText={(text) => onChangeText(text)}
value={value}
></TextInput>
</View>
<View>
<Button
mode="contained"
onPress={calculateTotal}
>
<Text>Calculate total</Text>
</Button>
</View>
</View>
<View>
<View>
<Button
mode="contained"
onPress={onSubmit}
>
<Text>Done</Text>
</Button>
</View>
<View>
<Button
title="Submit"
mode="contained"
>
<Text>Cancel</Text>
</Button>
</View>
</View>
</View>
</>
</View>
);
}
// export default Confirm;
Nothing looks wrong in your code but for safer side wrap try and catch inside useEffect.
useEffect(()=>{
try {
//Retrieving user token, reserved nanny information and user location value from AsyncStorage
AsyncStorage.multiGet(["token", "nany", "location"]).then((res) => {
var nany = JSON.parse(res[1][1]);
var location = JSON.parse(res[2][1]);
setInfo(nany);
console.log("hi3");
setSelectedLocation(location);
});
} catch (error) {
throw error;
}
,[]);

最新更新